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.
解析
Nim Game的游戏规则为每人每次可以拿走1 - 3
块石头,胜者为拿走最后一块石头的人。
我们可以从中得到:假设有两个人A、B在玩Nim Game,A先拿,判断A是否能够获胜。
- 石头总数为
1
时,A拿走1
块石头,A取得胜利 - 石头总数为
2
时,A拿走2
块石头,A取得胜利 - 石头总数为
3
时,A拿走3
块石头,A取得胜利 - 石头总数为
4
时,无论A拿走多少块石头,A都无法取得胜利 (A->3, B->1; A->2, B->2; A->1, B->3) - 石头总数为
5
时,A先拿走1
块石头,无论B拿走多少块石头,最终都是A取得胜利 - 石头总数为
6
时,A先拿走2
块石头,无论B拿走多少块石头,最终都是A取得胜利 - 石头总数为
7
时,A先拿走3
块石头,无论B拿走多少块石头,最终都是A取得胜利
…………
观察上面可以知道,当剩余石头的块数是4的倍数的时候,需要拿石头的人游戏胜利无望。因此,想要在这个游戏中赢,必须使得当对手拿石头的时候,剩余的石头总数是4的倍数。
因此,一开始判断自己是否能在游戏中胜出,那么只需判断此时的石头总数是否为4的倍数。
解决
class Solution {
public:
bool canWinNim(int n) {
if (n % 4 == 0) {
return false;
} else {
return true;
}
}
};