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.

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?

解题方法

类似coins in a line I, 找规律的题目

  • 如果n<=3, True
  • n == 4, False
  • 那么n == 5 or 6 or 7的时候, 都可以让下一个n为4这样自己就可以赢
  • 那么n == 8时,不管取多少对手都会在5,6,7之间必胜

所以规律就是如果是4的倍数就会输

Solution

class Solution(object):
    def canWinNim(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if not n:
            return True
        if n <= 3:
            return True

        if n % 4 == 0:
            return False
        else:
            return True

Reference