1. 程式人生 > >【兩次過】Lintcode 1300. Nim Game

【兩次過】Lintcode 1300. Nim Game

You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.

Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.

For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.

樣例

Input:
n=4
Output:
false

解題思路1:

第一眼就想到用動態規劃。設dp[i]為剩i個石頭時,能否贏。

最後一步:只能有扔1個石頭,2個石頭,3個石頭這三種情況

子問題:若扔掉1-3塊石頭之後,即dp[i-1],dp[i-2],dp[i-3]代表對方的輸贏情況,若其中中有一個贏,則dp[i]輸,若其中全為輸,則dp[i]贏。

狀態方程:dp[i] = !dp[i-1] || !dp[i-2] || !dp[i-3]

初始條件:dp[1] = true, dp[2] = true, dp[3] = true

public class Solution {
    /**
     * @param n: an integer
     * @return: whether you can win the game given the number of stones in the heap
     */
    public boolean canWinNim(int n) {
        // Write your code here
        //dp[i]為剩i個石頭時,能否贏
        boolean[] dp = new boolean[n+1];
        
        //初始條件
        dp[0] = false;
        if(n >= 1)
            dp[1] = true;
        if(n >= 2)
            dp[2] = true;
        if(n >= 3)
            dp[3] = true;
        
        //狀態方程
        for(int i=4; i<n+1; i++){
            dp[i] = !dp[i-1] || !dp[i-2] || !dp[i-3];
        }
        
        return dp[n];
    }
}

解題思路2:

發現規律,只有4及4的倍數才會輸。

public class Solution {
    /**
     * @param n: an integer
     * @return: whether you can win the game given the number of stones in the heap
     */
    public boolean canWinNim(int n) {
        // Write your code here
        return n%4 != 0;
    }
}