464. Can I Win
Description
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.
Solution
Game Theory
类题目。两个人轮流从 1-N
中选区数字,谁先得到和大于等于 total
的值,就是赢家。
Game Theory
类题目中,两个玩家都以最优的方式进行游戏,而且通常需要 memoization 做优化。
因为每个数字只能被选一次,所以需要记录那些数字被用过了。简单的方式可以用 set
,但是最 set
做备忘,开销比较大。因为数字的最大值为 20,所以可以使用 bitset
或 bitmap
做备忘。
在判断是否能够赢时,可以遍历当前可以选区的所有值,如果存在能赢的情况,则当前玩家能赢;反之,当前玩家一定输。
class Solution {
public:
bool canIWin(int maxChoosableInteger, int desiredTotal) {
// if maxnumber greater than desired number
if (maxChoosableInteger >= desiredTotal) {
return true;
}
// can't reach desiredTotal
if ((1 + maxChoosableInteger) * maxChoosableInteger / 2 < desiredTotal) {
return false;
}
return helper(0, maxChoosableInteger, 0, desiredTotal);
}
private:
bool helper(int state, int maxNumber, int sum, int total) {
// already calculated
if (memo_.count(state)) {
return memo_[state];
}
for (int i = 1; i <= maxNumber; ++i) {
if (state & (1 << (i - 1))) { // already used
continue;
}
auto new_state = (state | (1 << (i - 1)));
// 选取当前值后,直接能赢
// 选取当前值后,对方不能取胜,则当前玩家能赢
if (sum + i >= total || !helper(new_state, maxNumber, sum + i, total)) {
memo_[state] = true;
return true;
}
}
memo_[state] = false;
return false;
}
unordered_map<int, bool> memo_;
};