你正在和你的朋友,一共两人在玩Nim游戏:桌上有一个石碓,每一次只能移除1-3个石头。移除最后一个石头的为赢家。你是游戏开始之后第一个移动石头的人。
你和你的朋友都是很聪明的人,每一次都会选择最优的策略。写一个函数判断在给定石头个数的前提下你能否赢得比赛
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:本题是一道规律题
最后一次对手有的石头应该是4个,这样不管他怎么拿你都会赢,所以为了确保我能赢,我每次拿了之后剩下的石头数是4的倍数
则一开始石头数不是4的倍数(分析参考他人)
def canWinNim(self, n):
"""
:type n: int
:rtype: bool
"""
# if n % 4 == 0:
# return False
# else:
# return True
return False if n % 4 == 0 else True #与注释部分功能相同
算法题来自:https://leetcode-cn.com/problems/nim-game/description/