In the “100 game,” two players take turns adding, to a running total, any integer from 1…10. The player who first causes the running total to reach or exceed 100 wins.
What if we change the game so that players cannot re-use integers?
For example, two players might take turns drawing from a common pool of numbers of 1…15 without replacement until they reach a total >= 100.
Given an integer maxChoosableInteger and another integer desiredTotal, determine if the first player to move can force a win, assuming both players play optimally.
You can always assume that maxChoosableInteger will not be larger than 20 and desiredTotal will not be larger than 300.
Example
Input:
maxChoosableInteger = 10
desiredTotal = 11
Output:
false
Explanation:
No matter which integer the first player choose, the first player will lose.
The first player can choose an integer from 1 up to 10.
If the first player choose 1, the second player can only choose integers from 2 up to 10.
The second player will win by choosing 10 and get a total = 11, which is >= desiredTotal.
Same with other integers chosen by the first player, the second player will always win.
简而言之就是给出一个可选的最大数maxChoosableInteger,简称M,两个玩家从1~M中选一个数累加,数字不能重复,率先到达desiredTotal的玩家获胜。
问先选数字的玩家一能否赢。
思路:
玩家一和玩家二遵循游戏理论中的min-max, 即双方都走最有利于自己的,以player1的视角来看,要考虑player2走最利于player2自身利益的max, player1要尽量压低player2的max,也就是min-max。
而且双方玩家都要遍历所有可能的选项。player1只要有一个选项的结果能赢,就返回true。
如果考虑玩家先后顺序的话,有M! 的状态,如果不采用记忆,时间复杂度也是M!。
但是在游戏进行中的时候, player1先选1,player2后选2, 和player1先选2,player2后选1赢的可能性是一样的,所以压缩到2M
需要一个2M长度的状态来记录当前所选数字的组合是否已经有过,但是不必要用这么长的数组,可以用一个integer, 做bit操作,该bit位上是1证明该数字已经用过,用于记录使用过的数字
然后用一个2M长度的数组来记录一组数字组合下的输赢状态,记1为赢,-1为输,0为未知
player1每选一个数字,要遍历player2所有可能选的数字,同理player2选一个数后遍历player1所有可能选择的数字,这就用到递归
当遍历player2所有可能选择的数字后,player2仍然不能赢,那么player1就能赢,返回true,
遍历完player1可选的所有数字后,player2扔有可能赢,就认为player1不可能赢,返回false
class Solution {
private byte[] m; //用byte节省内存
public boolean canIWin(int maxChoosableInteger, int desiredTotal) {
if(desiredTotal <= 0) {
return true;
}
int M = maxChoosableInteger;
//1~M求和都不能>=desiredTotal,说明不能win
if(M * (M+1) / 2 < desiredTotal) {
return false;
}
//记忆player1 和 player2用过的所有数字组合状态
//0:未知,1:赢,-1:输
m = new byte[1<<M];
return canIWin(M, desiredTotal, 0);
}
//T:用过数字后剩下的desiredTotal, state:用过所有数字的组合,每个数字一个bit
public boolean canIWin(int M, int T, int state) {
if(T <= 0) {
return false;
}
//已经有结果的直接返回
if(m[state] != 0) {
return m[state] == 1;
}
//i从0开始,相当于试1~M所有的数
for(int i = 0; i < M; i++) {
//当前i已经用过
if((state & 1 << i) > 0) {
continue;
}
//看player2是否能赢
if(!canIWin(M, T-(i+1), state | 1 << i)) {
m[state] = 1; //该组合下player1赢
return true; //player2不能赢,则player1赢
}
}
m[state] = -1; //player1输
return false;
}
}