LeetCode Nim Game

Posted

tags:

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

Hint:

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

本体你只要确保倒数第5个你能拿,然后确保倒数9个你能拿。。以此类推,后面都是4的倍数,因而从后向前数,你只要保证能拿到最后一个是4的倍数的前面一个石头即可。

因而前面最多可以放3个石头,后面是4的倍数。所以只要石头的个数不能被4整除,你就能确保自己能赢

class Solution {
public:
    bool canWinNim(int n) {
        return n%4!=0;
    }
};

 

以上是关于LeetCode 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