LeetCode 292 Nim Game 解题报告

时间:2023-03-09 03:21:15
LeetCode 292 Nim Game 解题报告

题目要求

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.

题目分析及思路

给定石头的数量,要求确定‘我’是否能赢得比赛。比赛要求是‘我’和同伴每人轮流从一堆石头中取走1-3块,取走最后一块石头的是赢家。‘我’可以先取,且‘我’和同伴都有最优的策略。该比赛的关键在4,只要给对方剩下4块石头,这样对方就输了。所以只要确定石头数是否是4的倍数,又因为是‘我’先拿,综上只要石头数不是4的倍数,‘我’就是赢家。

python代码

class Solution:

def canWinNim(self, n: int) -> bool:

return n % 4 != 0

相关文章