原题说明
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number N on the chalkboard. On each player’s turn, that player makes a move consisting of:
Choosing any x
with 0 < x < N
and N % x == 0
.
Replacing the number N
on the chalkboard with N - x
.
Also, if a player cannot make a move, they lose the game.
Return True if and only if Alice wins the game, assuming both players play optimally.
Example 1:
Input:2
Output:true
Explanation: Alice chooses 1, and Bob has no more moves.
Example 2:
Input:3
Output:false
Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.
Note:
解题思路
如果N
为偶数,则坚持选择x = 1
,对方得到N - 1
为大于0
的奇数
如果N
为奇数:
- 如果
N > 1
, 其因子必然也是奇数,所以无论选择任何x
,N - x
都将变为偶数
由于x < N
,给予对方的N - x
必然是> 0
的偶数 - 如果
N = 1
,直接失败。
综上,N
为偶数时必然大于0
,只需要坚持选择x = 1
,最终对方会得到N = 1
而失败。
所以N
为偶数时返回true
。
用Flip Game II的方法也可以。
示例代码 (cpp)
1 | class Solution { |
示例代码 (java)
1 | class Solution { |
示例代码 (python)
1 | class Solution(object): |
复杂度分析
时间复杂度: O(1)
空间复杂度: O(1)
归纳总结
我们在Youtube上更新了视频讲解,欢迎关注!