2019-07-15 Divisor Game

Question

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

解题思路:本题通过动态规划

假设N=1,爱丽丝失败;先走输

假设N=2,她可以选择x=1,来使鲍勃遇到的N=2-1=1,无法操作,爱丽丝获胜;
先走胜

假设N=3,她只能选择x=1,鲍勃遇到的N=2,鲍勃获胜;

假设N=4,她可以选择x=1,来使鲍勃遇到的N=3,爱丽丝获胜

假设N=5,她可以选择X=1,来使鲍勃遇到的N=4,鲍勃获胜

然后往上计算

class Solution {
    public boolean divisorGame(int N) {
        boolean[] dp = new boolean[N + 1];
        dp[1] = false;
        for (int i = 2; i <= N; i++) {
            for (int j = 1; j < i; j++) {
                if (i % j == 0 && dp[i - j] == false) {
                    dp[i] = true;
                }
            }
        }
        return dp[N];
    }
}

你可能感兴趣的:(2019-07-15 Divisor Game)