1025. Divisor Game*

1025. Divisor Game*

https://leetcode.com/problems/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 <= N <= 1000

C++ 实现 1

这是逻辑思维题… 参考 just return N % 2 == 0 (proof) 解决. 其中有个评论解释的相当精彩:
https://leetcode.com/problems/divisor-game/discuss/274566/just-return-N-2-0-(proof)/262708

引用如下:

My reasoning is like this. Whoever loses for k will win for k+1, because he/she can choose 1 and the opponent will face the situation of k. The key point is that Alice loses if Bob wins, and Bob loses if Alice wins. As we know, Alice loses when the number is 1, therefore, when it is 2, Alice wins (because Alice loses when it is 1) and Bob loses. When the number is 3, Bob wins (because Bob loses when it is 2) and Alice loses. So on and so forth. We can conclude that Alice wins and Bob loses when k is even; Bob wins and Alice loses when k is odd.

所以代码很简洁:

class Solution {
public:
    bool divisorGame(int N) {
        return N % 2 == 0;
    }
};
发布了327 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Eric_1993/article/details/104523368