## 题目描述：

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.

Hint:

If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?

## 解题思路：

Nim游戏的解题关键是寻找“必胜态”。

```当n∈[1,3]时，先手必胜。

......

`当n % 4 != 0时，先手必胜；否则先手必负。`

## Python代码：

``````class Solution(object):
def canWinNim(self, n):
"""
:type n: int
:rtype: bool
"""
return n % 4 > 0
``````

Pingbacks已关闭。

1. 王晨曦 发布于 2016年6月22日 08:54 #

当8块石头时，先手拿1次拿3块，也是可以胜利的啊；
you：123 789 you win！！
friend： 456

2. 安超 发布于 2016年7月14日 10:45 #

you：123,；机智的friend：4,；还剩4个，you怎么赢？

3. 樊豆豆 发布于 2016年8月21日 16:39 #

先手拿3块，剩5块了，对手会拿1块，先手不就输了么