LeetCode Python 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~3个石子的时候。
  • 可你也是一个littleBitch:
    • 如果只剩5个及以上,你可以选择少拿,那么由于最多只能拿三个,那么对手将失败。
    • 但只有只剩4个石子的时候,由于游戏规则,你必须拿至少一个,所以对手胜。
  • 所以在心机婊的眼里,这个游戏的输赢在第一手就已经决定了。
  • 石子总数%4!=0,则先手必定获胜,获胜策略如下:
    • 第一手,拿取总数%4个石子。
    • 之后的每一轮,控制你和对手一轮拿取的总数==4,即:
      • 对手拿1你拿3
      • 对手拿2你拿2
      • 对手拿3你拿1
    • 你就可以体验心机婊控制别人的快感。
  • 反之,石子总数为4的倍数,则先手必输:
    • 后手直接在第一轮就将总数控制为4,则最后一定为胜。
class Solution:
    def canWinNim(self, n):
        """
        :type n: int
        :rtype: bool
        """
        return n%4!=0

猜你喜欢

转载自blog.csdn.net/weixin_41084236/article/details/81389660