leetcode 292
题目描述
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.
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.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/nim-game
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目分析
题目里要求我们根据石子数得到尼姆博弈的结果。首先我们可以将其看作一个回合制游戏,每一回合两个人各拿一次石子,由我先拿。
- 第一次想到的思路是用编程模拟整个游戏的过程,但是在选用石子采用什么策略是一个问题,刚开始使用随机选取的方式,但这样会导致获胜的结果也是随机的,游戏双方只是随缘玩游戏。这样显然是不行的,错误思路代码如下:
class Solution:
def canWinNim(self, n: int) -> bool:
count = n
while True:
if count - 1 == 0 or count - 2 == 0 or count - 3 == 0:
return True
else:
count -= random.randint(1, 3)
if count - 1 == 0 or count - 2 == 0 or count - 3 == 0:
return False
else:
count -= random.randint(1, 3)
- 分析多种情况后,我们发现获胜或失败是有规律的,只要石子数能被4整除,总存在一种方式使得对方获胜,也就是说如果石子数能被4整除,那么不管你每回合怎么拿石子,对方总能用一定的策略使得你的最后一回合时石子数为4,也就是说对方一定会获胜。这样问题就和简单了,一行代码就可以搞定,代码如下:
class Solution:
def canWinNim(self, n: int) -> bool:
return n % 4 != 0
- 上述代码还可以改进,直接看石子数二进制串的最后两位,如果存在1,则该数肯定不能被4整除
class Solution:
def canWinNim(self, n: int) -> bool:
x = bin(n).replace('0b', '')
return (x[-1] == '1' or x[-2] == '1')
另一种改进方式,本质上还是判断石子数能不能被4整除
class Solution:
def canWinNim(self, n: int) -> bool:
return n & 3
- 另外,也可以用递归、动态规划的思路来做
待补充