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.

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.

 

解题思路:

这是一道典型的博弈问题:如何行动能够获胜。

在这个游戏中,你可以拿走1,2,3个石头,最后一个拿走石头的人获胜。

那么我们可以对最基本的情况进行分析:

  当剩余0个石头时,都被对方拿走了:失败

  当剩余1个石头时,可以全拿走:胜利

  当剩余2个石头时,可以全拿走:胜利

  当剩余3个石头时,可以全拿走:胜利

  当剩余4个石头时,拿多少剩下的都会被全拿走(因为你和你的对手都足够聪明):失败

  

  当有其他数目的石头时,你可以想尽办法给你的对手留下4个石头,同样的你的对手由于足够聪明也会想尽办法留下4个石头给你。

 

代码:

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

 

posted @ 2018-06-23 01:05  妖域大都督  阅读(89)  评论(0编辑  收藏  举报