LeetCode刷题:1025. Divisor Game (JAVA动态规划算法)

LeetCode刷题: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

Alice和Bob一起玩游戏,他们轮流行动。Alice先手开局。

最初,黑板上有一个数字 N 。在每个玩家的回合,玩家需要执行以下操作:

选出任一 x,满足 0 < x < N 且 N % x == 0 。
用 N - x 替换黑板上的数字 N 。
如果玩家无法执行这些操作,就会输掉游戏。

只有Alice在游戏中取得胜利时才返回 True,否则返回 false。假设两个玩家都以最佳状态参与游戏。

 

示例 1:

输入:2
输出:true
解释:Alice选择 1,Bob无法进行操作。
示例 2:

输入:3
输出:false
解释:Alice选择 1,Bob也选择 1,然后Alice无法进行操作。


算法设计

public boolean divisorGame(int N) {
		// dp[i] -> can a player (whose turn is current) win with val 'i'
		boolean[] dp = new boolean[N + 1];
		for (int i = 2; i <= N; i++) {
			for (int j = 1; j <= Math.sqrt(i); j++) {
				// dp[i-j] == false, checks if the opponent loses with 'i-j'
				if ((i % j == 0) && (dp[i - j] == false)) {
					dp[i] = true;
					break;
				}
			}
		}
		return dp[N];
}

Accepted!

LeetCode刷题:1025. Divisor Game (JAVA动态规划算法)_第1张图片

你可能感兴趣的:(算法分析与设计,LeetCode)