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.
Show HintCredits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
状态1:假设是4个,己方无论怎样拿,必输.
状态2:假设是4的倍数,己方先拿,无论己方拿的数量x为多少,对手总能拿4-x个使得两者相加为4,那么最终会转变为上面的状态,必输.
状态3"假设是4的倍数,对手先拿,类比于状态2对手的策略,必胜.状态4:不是4的倍数,己方先拿,则甲方先拿走总数量对4取模的数,则能转换为状态3,必胜.
所以只要数量是4的倍数必输,反之必胜.
class Solution {
public:
bool canWinNim(int n) {
return n%4!=0;
}
};