版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/89315678
Description:
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和Bob每一步的选择都是最优的,我们考虑利用动态规划来实现,定义一个数组temp[N + 1]用于记录从1到N,Alice获胜的情况;下面给出了N从1到10的情况;
N | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
---|---|---|---|---|---|---|---|---|---|---|
Win(T/F) | F | T | F | T | F | T | F | T | F | T |
- N = 1时很容易理解,不存在这样的x,Alice判定为输;
- N = 2时,仅存在唯一的x=1满足条件,Alice经过这一个操作后,N = N - x = 1,由1知道轮到Bob时,找不到满足条件的x,Alice判断为赢;
- N = 3时,同2仅存在唯一的x=1满足条件,轮到Bob时N = N - x = 2,由2知道Alice判定为输
- N = 10时,满足条件的x={1,2,5},存在x=1使得Alice判定为赢
从上面的计算过程可以总结,每一个N的计算都依赖于前面[1,N-1]的结果;
Java
class Solution {
public boolean divisorGame(int N) {
boolean[] temp = new boolean[N + 1];
temp[1] = false;
for (int i = 2; i <= N; i++) {
for (int j = 1; j < i; j++) {
if (i % j == 0 && !temp[i - j]) {
temp[i] = true;
break;
}
}
}
return temp[N];
}
}
//当我计算了很多种情况后,发现N只要是偶数时,Alice就一定会赢
//至于证明,希望有人可以给出
//class Solution {
public boolean divisorGame(int N) {
return N % 2 == 0 ? true : false;
}
}