LeetCode 题解工作台
Nim 游戏
你和你的朋友,两个人一起玩 Nim 游戏 : 桌子上有一堆石头。 你们轮流进行自己的回合, 你作为先手 。 每一回合,轮到的人拿掉 1 - 3 块石头。 拿掉最后一块石头的人就是获胜者。 假设你们每一步都是最优解。请编写一个函数,来判断你是否可以在给定石头数量为 n 的情况下赢得游戏。如果可以赢,返…
3
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数学·结合·brainteaser
答案摘要
第一个得到 的倍数(即 能被 整除)的将会输掉比赛。 证明:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·结合·brainteaser 题型思路
题目描述
你和你的朋友,两个人一起玩 Nim 游戏:
- 桌子上有一堆石头。
- 你们轮流进行自己的回合, 你作为先手 。
- 每一回合,轮到的人拿掉 1 - 3 块石头。
- 拿掉最后一块石头的人就是获胜者。
假设你们每一步都是最优解。请编写一个函数,来判断你是否可以在给定石头数量为 n 的情况下赢得游戏。如果可以赢,返回 true;否则,返回 false 。
示例 1:
输入:n = 4
输出:false
解释:以下是可能的结果:
1. 移除1颗石头。你的朋友移走了3块石头,包括最后一块。你的朋友赢了。
2. 移除2个石子。你的朋友移走2块石头,包括最后一块。你的朋友赢了。
3.你移走3颗石子。你的朋友移走了最后一块石头。你的朋友赢了。
在所有结果中,你的朋友是赢家。
示例 2:
输入:n = 1 输出:true
示例 3:
输入:n = 2 输出:true
提示:
1 <= n <= 231 - 1
解题思路
方法一:找规律
第一个得到 的倍数(即 能被 整除)的将会输掉比赛。
证明:
- 当 时,第一个玩家可以直接拿走所有的石头,所以第一个玩家将会赢得比赛。
- 当 ,无论第一个玩家选择 哪个数字,第二个玩家总能选择剩下的数字,所以第一个玩家将会输掉比赛。
- 当 时,即 ,第一个玩家可以相应地将数字减少为 ,那么 这个死亡数字给到了第二个玩家,第二个玩家将会输掉比赛。
- 当 ,无论第一个玩家选择 哪个数字,都会把 的数字留给第二个,所以第一个玩家将会输掉比赛。
- ...
- 依次类推,当玩家拿到 这个数字,且 能被 整除,他将会输掉比赛,否则他将赢得比赛。
时间复杂度 ,空间复杂度 。
class Solution:
def canWinNim(self, n: int) -> bool:
return n % 4 != 0
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
A correct approach identifies the modulo 4 pattern for optimal play.
- question_mark
The candidate should recognize the game theory basis for the solution.
- question_mark
Candidates who try brute force simulations instead of a mathematical solution may need further guidance.
常见陷阱
外企场景- error
Overcomplicating the solution by simulating all possible moves instead of using the modulo 4 strategy.
- error
Failing to recognize that the winning and losing positions are based on multiples of 4.
- error
Misunderstanding the alternating nature of the game and assuming a winning strategy when n % 4 == 0.
进阶变体
外企场景- arrow_right_alt
What if players can remove 1, 2, or 3 stones, but the first player can remove up to 4 stones?
- arrow_right_alt
How would the game change if there were more than 3 players, all taking turns to remove stones?
- arrow_right_alt
What happens if the first player can only remove 1 stone per turn?