LeetCode 464. Can I Win 【博弈 + 状压DP】

题目链接:我能赢吗 - 力扣 (LeetCode)

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.

题意:
两个人从1~maxChoosableInteger中任选一个数字,第一个人先选,第二个人后选,每个数只能被选一次。两个人谁选的数字总和超过desiredTotal谁就赢,问在两个人都采用最佳策略的情况下,第一个人能否赢得比赛

分析:
对于当前状态,如果能走到对手的必败态,则当前状态为必胜态
如果能走到的全部为对手的必胜态,则当前状态为必败态
状态压缩一般需要从0到n,所以这里用i+1代表maxn
状态的改变:status |= (1 << i);
状态的恢复:status ^= (1 << i);status -= (1 << i);status += (1 << i);

class Solution {
public:
    bool canIWin(int max, int desire) {
        int status = 0;
        if (desire <= 1) return true;
        if (max * (max + 1) < desire*2) return false;
        vector<unordered_map<int,bool>> dp(desire + 1);
        return Caniwin(status, dp, max, desire);
    }
    bool Caniwin(int status, vector<unordered_map<int,bool>>&dp, int maxn, int desire){
        if (dp[desire].count(status))
            return dp[desire][status];
        for (int i = maxn-1; i >= 0; --i){
            if (!(status & (1 << i))){
                status |=  (1 << i);
                if (i + 1 >= desire || !Caniwin(status, dp, maxn, desire-i-1)) {
                    dp[desire][status] = true;
                    return true;
                }
                status ^= (1 << i);
            }
        }
        dp[desire][status] = false;
        return false;
    }
};

你可能感兴趣的:(DFS,数论,位运算,LeetCode,动态规划,博弈,LeetCode,题解,C++版)