LeetCode 292. Nim Game

292. Nim Game 尼姆游戏

You are playing the following Nim Game with your friend:
您正在和您的朋友玩以下NIM游戏:
There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones.
桌上有一堆石头,你们中的每一个人轮流移动1到3块石头。
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块石头,那么你将永远无法赢得比赛;无论你移除1块、2块或3块石头,最后一块石头都将被你的朋友移除。

思路

n=1,2,3时你赢,n=4时对手赢;

n=5时,根据上一点,你只需先拿走1个石子,于是剩下4个,由于“n=4时对手赢”,而对手的对手是你,因此你必赢;

n=6,7时同理;

n=8时,你有3种选择,结果分别剩下7,6,5个石子,此时对手站在你的角度,根据上面结论,对手必赢。

……如何循环下去,你总是3赢1输。

code

class Solution {
public:
    bool canWinNim(int n) {
        return n%4;
    }
};
原文地址:https://www.cnblogs.com/AlexKing007/p/12338419.html