292 Nim Game

1 题目

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.

2 尝试解

2.1 分析

一堆石头,我和对手轮流取,一次取1-3个,取到最后一个石头的人赢,我先取。石头数1-3时,我直接取完获胜。石头数为4时,我怎么样取都不会获胜。所以如果让对手面临4,我就能赢,否则我就会输。再推广,如果石头数是4n+1,2,3,那么我将余数取掉,并且保证之后每一次博弈和对手取得石头数之和为4,那么对手将面临4,我会赢。同理,如果石头数是4n,那么对手每轮和我取的石头数之和为4,最后我将面临4,会输掉。所以面临4n的人会输掉。

2.2 代码

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

猜你喜欢

转载自blog.csdn.net/weixin_39145266/article/details/89499321
今日推荐