292. Nim 游戏
https://leetcode-cn.com/problems/nim-game/
你和你的朋友,两个人一起玩 Nim 游戏:桌子上有一堆石头,每次你们轮流拿掉 1 - 3 块石头。 拿掉最后一块石头的人就是获胜者。你作为先手。
你们是聪明人,每一步都是最优解。 编写一个函数,来判断你是否可以在给定石头数量的情况下赢得游戏。
示例:输入: 4,输出: false,解释: 如果堆中有 4 块石头,那么你永远不会赢得比赛;因为无论你拿走 1 块、2 块 还是 3 块石头,最后一块石头总是会被你的朋友拿走。
题解
一:我们发现只要他前面三个树木中有一个是False,则可以赢,但是未通过,内存占用太多。
class Solution(object):
def canWinNim(self, n):
"""
:type n: int
:rtype: bool
"""
if n <= 3:
return True
res = [False] * (n + 1)
for i in range(1, 4):
res[i] = True
for i in range(4, n + 1):
res[i] = False
for j in range(1, 4):
if not res[i - j]:
res[i] = True
break
return res[-1]
优化:我们发现只和最近的三个数字有关,故没必要存储所有的数字。还是没通过。
class Solution(object):
def canWinNim(self, n):
if n <= 3:
return True
rec = [True] * 3
res = False
for i in range(4, n + 1):
res = False
for j in range(3):
if not rec[j]:
res = True
break
print((i, res), " ")
for j in range(2):
rec[j] = rec[j + 1]
rec[-1] = res
return res
优化:有一种感觉数字间必定存在某种规律,打印出了前100的值,发现凡是除了4的倍数都能赢。这次通过了。真数学题。
class Solution(object):
def canWinNim(self, n):
return n % 4