292. Nim Game

question:

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.

answer:

当石子数为1,2,3时,先手可一次拿走,先手必胜;

当石子数为4时,不论先手拿1,2,还是3,后手必胜;

当石子数为5是,先手先拿一个,后手面对石子数为4的情况,先手必胜;

......

所以,当石子数是4的倍数时,后手必胜,否则先手胜。

后手获胜的策略为:每次取石子的数量,与上一次先手所取石子的数量相加为4.

先手获胜的策略为:每次取石子的数量,都令剩余石子的数量为4的倍数。

class Solution {
public:
    bool canWinNim(int n) {
        if(n%4==0)
        return false;
        else
        return true;
        
    }
};

 

posted @ 2016-06-28 20:47  绵绵思远道  阅读(130)  评论(0编辑  收藏  举报