464 Can I Win
464. Can I Win
1. Question
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 integermaxChoosableInteger
and another integerdesiredTotal
, determine if the first player to move can force a win, assuming both players play optimally.
You can always assume thatmaxChoosableInteger
will not be larger than 20 anddesiredTotal
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.
2. Implementation
(1) Memoization + Bit Manipulation
思路:
1.Base case: 这题问第一个玩家是否能赢,赢的条件是在可选的数里,找到和大于desiredTotal即可。两个比较容易想到的base case是
(1) maxChoosableInteger大于desiredTotal时,玩家肯定能赢(第一轮就选maxChoosableInteger)
(2) 将1 - maxChoosableInteger的和相加,如果小于desiredTotal两个玩家都赢不了
2.用Bit表示状态:
class Solution {
public boolean canIWin(int maxChoosableInteger, int desiredTotal) {
if (maxChoosableInteger >= desiredTotal) return true;
if (maxChoosableInteger * (maxChoosableInteger + 1) / 2 < desiredTotal) return false;
int[] cache = new int[1 << maxChoosableInteger];
return canWin(maxChoosableInteger, desiredTotal, 0, cache);
}
public boolean canWin(int max, int target, int state, int[] cache) {
if (target <= 0) {
return true;
}
if (cache[state] != 0) {
return cache[state] == 1;
}
for (int i = max; i >= 1; i--) {
int code = (1 << (i - 1));
// If the current number has been used, skip it
if ((code & state) != 0) continue;
// If the current state will make first player win, update cache and return true
if (target <= i || !canWin(max, target - i, state | code, cache)) {
cache[state] = 1;
return true;
}
}
cache[state] = -1;
return false;
}
}
3. Time & Space Complexity
Memoization: 时间复杂度O(2 ^ n), 空间复杂度O(2 ^ n)
Last updated
Was this helpful?