[Leetcode 1025] Divisor Game

原题说明

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:

  1. 1 <= N <= 1000

解题思路

如果N为偶数,则坚持选择x = 1,对方得到N - 1为大于0的奇数
如果N为奇数:

  1. 如果N > 1, 其因子必然也是奇数,所以无论选择任何xN - x都将变为偶数
    由于x < N,给予对方的N - x必然是 > 0的偶数
  2. 如果N = 1,直接失败。
    综上,N为偶数时必然大于0,只需要坚持选择x = 1,最终对方会得到N = 1而失败。
    所以N为偶数时返回true

用Flip Game II的方法也可以。

示例代码 (cpp)

1
2
3
4
5
6
class Solution {
public:
bool divisorGame(int N) {
return N % 2 == 0;
}
};

示例代码 (java)

1
2
3
4
5
class Solution {
public boolean divisorGame(int N) {
return N % 2 == 0;
}
}

示例代码 (python)

1
2
3
4
5
6
7
class Solution(object):
def divisorGame(self, N):
"""
:type N: int
:rtype: bool
"""
return N % 2 == 0

复杂度分析

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

归纳总结

我们在Youtube上更新了视频讲解,欢迎关注!

------ 关注公众号:猩猩的乐园 ------