LC464. Can I Win
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.
这个问题和Nim game有点像,但是那题recursion可解,这题TLE。再次拜倒在discuss的答案之下。
利用n位比特来记录某个数是否使用过,map记录当前status先手是否能赢。
public class Solution {
public boolean canIWin(int n, int total) {
if(total <= 1) return true;
if(total > n*(n+1)/2) return false;
// use bit to save status
Boolean[] map = new Boolean[1 << n];
return canWin(total, n, 0, map);
}
private boolean canWin(int remain, int n, int status, Boolean[] map){
if(map[status] != null) return map[status];
for(int i = n; i >= 1; i--){
int bit = 1 << (i-1);
// can use this number
if((status & bit) == 0){
if(i >= remain){
map[status] = true;
return true;
}
status ^= bit;
boolean oppwin = canWin(remain - i, n, status, map);
status ^= bit;
if(!oppwin){
map[status] = true;
return true;
} // if
} // if
} // for
map[status] = false;
return false;
}
}
O(1 « n), O(1 « n)