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.
一开始我是用斐波那契数列思路求解,因为f(n) = !f(n-1) or !f(n-2) or !f(n-3),但是经过深入观察发现,答案的规律就在于数字是否为4的倍数。面试遇到这种题目就只能多多观察,总结规律再下手!
class Solution(object): def canWinNim(self, n): """ :type n: int :rtype: bool """ # 1,2,3 => true # 4 => false # 5,6,7 => true, =1,2,3+f(4) # 8 => 1,2,3+f(5,6,7) = false # 9 => 1,2,3+f(6,7,8) = true # 10 => 1+2,3+f(9,8,7) = true # 11 => 1,2,3+f(10,9,8) = true # 12 => 1,2,3+f(11,10,9) = false # 13 => 1,2,3+f(12,11,10) = true # 14 => 1,2,3+f(13,12,11) = true # 15 => # rule: 3true 1false 3true 1false ... return n % 4 != 0 # iter solution, but time limit if n <= 3: return True a = b = c = True for i in xrange(4, n+1): t = (not a) or (not b) or (not c) a = b b = c c = t return c
4的倍数还可以 return (n & 0b11) != 0;