力扣 464. 我能赢吗(c++ bitset记忆化搜索)

力扣 464. 我能赢吗(c++ bitset记忆化搜索)_第1张图片
力扣 464. 我能赢吗(c++ bitset记忆化搜索)_第2张图片
bitset用法链接1
bitset用法链接2

class Solution {
public:
    int a,b;
    unordered_map<unsigned long long,bool> mp;
    bool dfs(int sum,bitset<25> bs){
        if(sum >= b) return true;
        if(mp.find(bs.to_ullong()) != mp.end()) return mp[bs.to_ullong()];
        int res = true;
        for(int i = 1;i <= a;i++){
            if(bs[i]) continue;
            bitset<25> bs1;
            bs1 = bs;
            bs1[i] = 1;
            if(dfs(sum + i,bs1)){
                res = false;
                break;
            }
        }
        return mp[bs.to_ullong()] = res;
    }
    bool canIWin(int maxChoosableInteger, int desiredTotal) {
        a = maxChoosableInteger,b = desiredTotal;
        if((a + 1) * a * 0.5 < b) return false;
        for(int i = 1;i <= a;i++){
            bitset<25> bs;
            bs[i] = 1;
            if(dfs(i,bs)) return true;
        }
        return false;
    }
};

你可能感兴趣的:(深度优先搜索,Leetcode,记忆化数组)