464 Can I Win 我能赢吗

时间:2021-10-22 21:42:22

详见:https://leetcode.com/problems/can-i-win/description/

C++:

class Solution {
public:
bool canIWin(int maxChoosableInteger, int desiredTotal)
{
if (maxChoosableInteger >= desiredTotal)
{
return true;
}
if (maxChoosableInteger * (maxChoosableInteger + 1) / 2 < desiredTotal)
{
return false;
}
unordered_map<int, bool> m;
return canWin(maxChoosableInteger, desiredTotal, 0, m);
}
bool canWin(int length, int total, int used, unordered_map<int, bool>& m)
{
if (m.count(used))
{
return m[used];
}
for (int i = 0; i < length; ++i)
{
int cur = (1 << i);
if ((cur & used) == 0)
{
if (total <= i + 1 || !canWin(length, total - (i + 1), cur | used, m))
{
m[used] = true;
return true;
}
}
}
m[used] = false;
return false;
}
};

参考:https://www.cnblogs.com/grandyang/p/6103525.html