forked from tcandzq/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNimGame.py
More file actions
34 lines (27 loc) · 1.03 KB
/
NimGame.py
File metadata and controls
34 lines (27 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
"""
题号 292 Nim游戏
你和你的朋友,两个人一起玩 Nim 游戏:桌子上有一堆石头,每次你们轮流拿掉 1 - 3 块石头。 拿掉最后一块石头的人就是获胜者。你作为先手。
你们是聪明人,每一步都是最优解。 编写一个函数,来判断你是否可以在给定石头数量的情况下赢得游戏。
示例:
输入: 4
输出: false
解释: 如果堆中有 4 块石头,那么你永远不会赢得比赛;
因为无论你拿走 1 块、2 块 还是 3 块石头,最后一块石头总是会被你的朋友拿走。
参考:https://leetcode-cn.com/problems/nim-game/solution/nimyou-xi-by-leetcode/
"""
class Solution:
# 丑陋版
def canWinNim(self, n: int) -> bool:
if n <= 3:
return True
elif n % 4 == 0:
return False
else:
return True
# 优雅版
def canWinNim2(self, n: int) -> bool:
return n % 4 != 0
if __name__ == '__main__':
n = 4
solution = Solution()
print(solution.canWinNim(n))