LeetCode 题解工作台

除数博弈

爱丽丝和鲍勃一起玩游戏,他们轮流行动。爱丽丝先手开局。 最初,黑板上有一个数字 n 。在每个玩家的回合,玩家需要执行以下操作: 选出任一整数 x ,满足 0 且 n % x == 0 。 用 n - x 替换黑板上的数字 n 。 如果玩家无法执行这些操作,就会输掉游戏。 只有在爱丽丝在游戏中取得胜利…

category

4

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 状态·转移·动态规划

bolt

答案摘要

- 当 ,先手败 - 当 ,先手拿 ,剩下 ,后手败,先手胜

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

爱丽丝和鲍勃一起玩游戏,他们轮流行动。爱丽丝先手开局。

最初,黑板上有一个数字 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
lightbulb

解题思路

方法一:数学归纳法

  • n=1n=1,先手败
  • n=2n=2,先手拿 11,剩下 11,后手败,先手胜
  • n=3n=3,先手拿 11,剩下 22,后手胜,先手败
  • n=4n=4,先手拿 11,剩下 33,后手败,先手胜
  • ...

猜想,当 nn 为奇数时,先手败;当 nn 为偶数时,先手胜。

证明:

  1. n=1n=1n=2n=2,结论成立;
  2. n>2n \gt 2,假设 nkn \le k 时,该结论成立,则 n=k+1n=k+1 时:
    • k+1k+1 为奇数,由于 xxk+1k+1 的因数,那么 xx 只可能是奇数,因此 k+1xk+1-x 为偶数,后手胜,先手败;
    • k+1k+1 为偶数,此时 xx 既可以是奇数 11,也可以是偶数,若 xx 取奇数,那么 k+1xk+1-x 为奇数,后手败,先手胜。

综上,当 nn 为奇数时,先手败;当 nn 为偶数时,先手胜。结论正确。

时间复杂度 O(1)O(1),空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def divisorGame(self, n: int) -> bool:
        return n % 2 == 0
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

除数博弈题解:状态·转移·动态规划 | LeetCode #1025 简单