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;
}
}