Game divisor

description:

Alice and Bob play a game, they take turns. Alice upper hand start.

Initially, there is a number N on the board. In each player's turn, the player needs to do the following:

Is selected as an x, satisfying 0 <x <N, and N% x == 0.
Replacement digital x N on the board - with N.
If the player can not perform these operations, it will lose the game.

Only Alice returns True only when the victory in the game, otherwise false. Suppose that two players are in the best state to participate in the game.

Example 1:

Input: 2
Output: true
interpretation: Alice select 1, Bob can not operate.

Example 2:

Input: 3
Output: false
interpretation: Alice select 1, Bob also select one, then Alice can not operate.

prompt:

1 <= N <= 1000

Ideas:

This question can be solved in two ways, one is mathematical induction, one is dynamic programming, dynamic programming here is mainly about.

Mathematical induction:

The end result should be accounted win 2, 1, accounts for transmission;

If the current is odd, odd divisor is odd or only 1, so that the next must be even;

If the current number is about even, even-odd may be an even number may be 1, thus directly minus 1, then the next is odd;

Therefore, it is odd to lose, even then win.

Dynamic Programming:

All solutions are less than or equal to N to find out, based on the foregoing, the recursive later.

State transition: If there are about several i is present to False (i.e., the case of losing), should the current i is True; if if not, and False

java:

class Solution {
    public boolean divisorGame(int N) {
        if (N <= 1) {
            return false;
        }
        if (N == 2) {
            return true;
        }
        boolean[] tag = new boolean[N + 1];
        tag[1] = true;
        tag[2] = false;

        for (int i = 3; i < tag.length; i++) {
            Tag [i] = to false ;
             // divisor range, when more than i / 2, about the number i is not present 
            for ( int J =. 1; J <i / 2; J ++ ) {
                 IF (i == 0 && J% Tag [I - J] == to false ) {
                    tag[i] = true;
                    break;
                }
            }
        }
        return tag[N];
    }
}

result:

python3:

class Solution:
    def divisorGame(self, N: int) -> bool:
        if N == 1:
            return False
        if N == 2:
            return True
        tag = [False for i in range(0, N + 1)]
        tag[2] = True
        for i in range(3, N + 1):
            for j in range(1, i // 2):
                if i % 2 == 0 and tag[i - j] == False:
                    tag[i] = True
                    break
        return tag[N]

result:

 

 

 

Guess you like

Origin www.cnblogs.com/nedulee/p/11992656.html