https://leetcode.com/problems/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
maxChoosableIntegerand another integerdesiredTotal, determine if the first player to move can force a win, assuming both players play optimally.You can always assume that
maxChoosableIntegerwill not be larger than 20 anddesiredTotalwill 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.
可用简单博弈法,注意处理双方皆不可赢的情况
class Solution {
public:
int used;
int pool, target;
unordered_map<int, bool> IM, UM;
bool canIWin(int maxChoosableInteger, int desiredTotal) {
if(desiredTotal == 0) return true;
if((1+maxChoosableInteger)*maxChoosableInteger/2 < desiredTotal) return false;
used = 0;
pool = maxChoosableInteger;
target = desiredTotal;
return IMove(0,0);
}
bool IMove(int cur, int used){ // exist
if(cur >= target) return false;
if(IM.find(used) != IM.end()){
return IM[used];
}
for(int i = 1; i <= pool; ++i){
if((used & (1 << (i-1))) != 0) continue;
bool tem = UMove(cur+i, (used | (1 << (i-1))));
if(tem == true){
IM[used] = true;
return true;
}
}
IM[used] = false;
return false;
}
bool UMove(int cur, int used){
if(cur >= target) return true;
if(UM.find(used) != UM.end()){
return UM[used];
}
for(int i = 1; i <= pool; ++i){
if((used & (1 << (i-1))) != 0) continue;
bool tem = IMove(cur+i, (used | (1 << (i-1))));
if(tem == false){
UM[used] = false;
return false;
}
}
UM[used] = true;
return true;
}
};
本文探讨了100游戏中,两位玩家如何在不能重复使用数字的情况下,通过最优策略决定胜负。游戏的目标是使总和达到或超过100,而每位玩家从1到指定的最大可选整数中选择数字。文章详细分析了如何判断先手玩家是否能确保胜利,并提供了算法实现。
1300

被折叠的 条评论
为什么被折叠?



