LeetCode 题解工作台
除数博弈
爱丽丝和鲍勃一起玩游戏,他们轮流行动。爱丽丝先手开局。 最初,黑板上有一个数字 n 。在每个玩家的回合,玩家需要执行以下操作: 选出任一整数 x ,满足 0 且 n % x == 0 。 用 n - x 替换黑板上的数字 n 。 如果玩家无法执行这些操作,就会输掉游戏。 只有在爱丽丝在游戏中取得胜利…
4
题型
5
代码语言
3
相关题
当前训练重点
简单 · 状态·转移·动态规划
答案摘要
- 当 ,先手败 - 当 ,先手拿 ,剩下 ,后手败,先手胜
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
爱丽丝和鲍勃一起玩游戏,他们轮流行动。爱丽丝先手开局。
最初,黑板上有一个数字 n 。在每个玩家的回合,玩家需要执行以下操作:
- 选出任一整数
x,满足0 < x < n且n % x == 0。 - 用
n - x替换黑板上的数字n。
如果玩家无法执行这些操作,就会输掉游戏。
只有在爱丽丝在游戏中取得胜利时才返回 true 。假设两个玩家都以最佳状态参与游戏。
示例 1:
输入:n = 2 输出:true 解释:爱丽丝选择 1,鲍勃无法进行操作。
示例 2:
输入:n = 3 输出:false 解释:爱丽丝选择 1,鲍勃也选择 1,然后爱丽丝无法进行操作。
提示:
1 <= n <= 1000
解题思路
方法一:数学归纳法
- 当 ,先手败
- 当 ,先手拿 ,剩下 ,后手败,先手胜
- 当 ,先手拿 ,剩下 ,后手胜,先手败
- 当 ,先手拿 ,剩下 ,后手败,先手胜
- ...
猜想,当 为奇数时,先手败;当 为偶数时,先手胜。
证明:
- 若 或 ,结论成立;
- 若 ,假设 时,该结论成立,则 时:
- 若 为奇数,由于 是 的因数,那么 只可能是奇数,因此 为偶数,后手胜,先手败;
- 若 为偶数,此时 既可以是奇数 ,也可以是偶数,若 取奇数,那么 为奇数,后手败,先手胜。
综上,当 为奇数时,先手败;当 为偶数时,先手胜。结论正确。
时间复杂度 ,空间复杂度 。
class Solution:
def divisorGame(self, n: int) -> bool:
return n % 2 == 0
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on how efficiently we calculate divisors and transition states. The space complexity depends on the dynamic programming array size, which is O(n). |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for understanding of game theory and dynamic programming concepts.
- question_mark
Check if the candidate can optimize the approach beyond brute force.
- question_mark
Assess the candidate’s ability to recognize patterns in state transitions.
常见陷阱
外企场景- error
Not considering the impact of parity (even/odd) in game decisions.
- error
Overcomplicating the problem by calculating all divisors instead of focusing on state transitions.
- error
Failing to optimize space usage with dynamic programming.
进阶变体
外企场景- arrow_right_alt
Extend the problem to multiple players instead of just Alice and Bob.
- arrow_right_alt
Consider the case where players can subtract any divisor instead of only the proper ones.
- arrow_right_alt
Introduce a restriction on the number of moves a player can make.