Leetcode 292. Nim Game

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 292. 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.

即,两人取石头,石头总数一定,每人每次可以取1~3个,拿到最后一个石头的人获胜。

易得,当剩下四个石头时,第二个取石头的人一定获胜,且每一个回合,不管第一个人拿几个,肯定这个回合总数可以为4。所以先取石头的人只要保证剩下的石头数是4的整数即可。

 

C++代码如下:

class Solution {
public:
    bool canWinNim(int n) {
        return n%4?true:false;
    }
};

 

以上是关于Leetcode 292. Nim Game的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 292. Nim Game

Leetcode-292 Nim Game

Leetcode 292. Nim Game

LeetCode 292 Nim Game

LeetCode 292. Nim Game

LeetCode #292. Nim Game