qianlei90 / Blog

那些该死的文字呦
https://qianlei.notion.site
103 stars 20 forks source link

292. Nim Game #25

Open qianlei90 opened 7 years ago

qianlei90 commented 7 years ago

292. Nim Game

Tags: 印象笔记

[toc]


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.

hint

If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?

Solution

其实就是找规律.

石子数 先手者赢 说明
1 True
2 True
3 True
4 False 不管A取几个, B总是[1, 2, 3], 相当于在[1, 2, 3]时B先手
5 True A取1, B会到4, 相当于在4时B先手, 会输
6 True A取2, 同上
7 True A取3, 同上
8 False 不管A取几个, B总是[5, 6, 7], 相当于在[5, 6, 7]时B先手
9 True A取1, B会到8, 相当于在8时B先手, 会输
... ... ...

Show me the code

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

- 完 -