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.
首先我想到用动态规划来做,但在草稿纸上试了几个之后发现,这是一道数学问题。要保证自己能赢,那就必须保证我拿完倒数第二次后,还剩4个石头;这就要求我拿倒数第二次之前,石头的个数为5、6、7中的一种;这就要求我拿完倒数第三次后,还剩8个石头.......以此类推,要求在我第一次拿之前,石头的个数为4n+1或4n+2或4n+3,即不能是4的倍数。发现这点之后,直接一行代码即可解决。
class Solution:
def canWinNim(self, n: int) -> bool:
return n % 4 != 0