LeetCode 1025. Divisor Game
考点 | 难度 |
---|---|
Dynamic Programming | Easy |
题目
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.
思路
用i
表示这一轮剩余的数字,j
表示玩家选择的数字。每一轮选择的j
必须满足i%j == 0
。选择后对方剩余的数字是i - j
。用dp
储存对于每一个i
的胜负情况,最后返回dp[N]
。
答案
public boolean divisorGame(int N) {
boolean[] dp = new boolean[N+1];
for(int i=1;i<=N;i++)
{
if(i==1) dp[i]=false;
else if(i==2) dp[i]=true;
else{
for(int j=1;j*j<=i;j++)
{
if(i%j==0)
{
dp[i] = !dp[i-j];
break;
}
}
}
}
return dp[N];
}