0292. Nim Game (E)
Nim Game (E)
题目
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.
Example:
Input: 4
Output: false
Explanation: 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-3个石子,取到最后一个石子的人获胜。给定n个石子,问如果你先取,能否获胜。
思路
找规律:
1胜 2胜 3胜 4败 5胜 6胜 7胜 8败 9胜 10胜 ...
简单规律就是当n为4的倍数时会输。
假设共有n个石子,每个人一次可取1-m个,那么显然当n=(m+1)k时,先取的人必败,因为后取的人总是可以将该轮取走的石子总数控制为m+1;而当n=(m+1)k+x时,只要先取的人只取x个,情况就变成了相当于后取的人从(m+1)k个石子开始取,这样先取的人总能控制每轮取走总数为m+1,从而能保证胜利。
代码实现
Java
class Solution {
public boolean canWinNim(int n) {
return n % 4 != 0;
}
}