leetcode解题: Nim Game (292)

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.

解法1:DP with O(N) time, N is the number of input, Runtime Error

思路就是去试几个不同的数,找出规律。自然的首先想到的是DP的算法,比如输入4,那么无论如何不能达到。如果是5,那么只要1可以,那么5就可以。似乎只需要看前面差4个数的结果。x[i] = x[i - 4],但是当数据变大的时候会出现Runtime error。
C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
bool canWinNim(int n) {
if (n <= 0) {
return false;
}
if (n <= 3) {
return true;
}
bool x[n + 1];
x[0] = false; x[1] = true; x[2] = true; x[3] = true;
for (int i = 4; i <= n; i++) {
x[i] = x[i - 4];
}
return x[n];
}
}

解法2:O(1) Time with Math

1,2,3 可以,4 false, 5,6,7 true, 8 false. 得出的结论是能除4的就不能赢。
C++

1
2
3
4
5
6
class Solution {
public:
bool canWinNim(int n) {
return n % 4 != 0;
}
};