292. Nim Game(尼姆游戏)

版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/xunalove/article/details/79378781

题目

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.

题意

你正在和你的朋友玩尼姆游戏:桌子上有一堆石子,你们轮流拿走1~3块石子。拿走最后一块石子的人将是胜利者。你将在第一个轮回拿走石子。
你们两个都很聪明,有最佳的游戏策略。写一个函数来决定你是否可以赢得比赛。
举个例子,如果堆里有4块石头,那么你永远赢不了这场比赛:不管你拿走1, 2块或3块石头,最后一块石头都会被你的朋友拿走。

题解

石头1块 胜
石头2块, 胜
石头3块, 胜
石头4块, 不管你拿走1, 2块或3块石头,最后一块石头都会被你的朋友拿走,败
石头5块,你先拿1块,剩下4块,不管对方拿走1, 2块或3块石头,最后一块石头都会被你拿走,胜
石头6块,你先拿2块,剩下4块,不管对方拿走1, 2块或3块石头,最后一块石头都会被你拿走,胜
石头7块, 你先拿3块,剩下4块,不管对方拿走1, 2块或3块石头,最后一块石头都会被你拿走,胜
石头八块,对于4个石子,败,后4个石子,败,肯定败
……….
从上面可以看出,只有石子总数是4的倍数时你才会输。

C++代码

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

python代码

class Solution(object):
    def canWinNim(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n % 4 != 0:
            return True
        return False

猜你喜欢

转载自blog.csdn.net/xunalove/article/details/79378781
今日推荐