LeetCode--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.

代码:

    bool canWinNim(int n) {
        if(n%4 == 0)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
1.  n = 1,2, 3时,自己赢.

2.  n = 4,无论自己拿对少都是对方赢.

3. n = 5,6,7,自己分别拿1, 2, 3个,对方剩余4个,面对的是自己的第二种情况,因此自己赢

4. n = 8, 自己无论拿多少,对方剩余5, ,6 ,7个,面对第三种情况,因此对方赢.

5. n = 9. 10. 11.....

...一直循环,因此每当4的倍数就是对方赢.



posted on 2015-11-03 10:32  小二杰  阅读(125)  评论(0编辑  收藏  举报

导航