forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
can-i-win.cpp
35 lines (32 loc) · 1.07 KB
/
can-i-win.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Time: O(n!)
// Space: O(n)
class Solution {
public:
bool canIWin(int maxChoosableInteger, int desiredTotal) {
if ((1 + maxChoosableInteger) * (maxChoosableInteger / 2) < desiredTotal) {
return false;
}
unordered_map<int, int> lookup;
return canIWinHelper(maxChoosableInteger, desiredTotal, 0, &lookup);
}
private:
int canIWinHelper(int maxChoosableInteger, int desiredTotal,
int visited, unordered_map<int, int> *lookup) {
if (lookup->find(visited) != lookup->end()) {
return (*lookup)[visited];
}
int mask = 1;
for (int i = 0; i < maxChoosableInteger; ++i) {
if (!(visited & mask)) {
if (i + 1 >= desiredTotal ||
!canIWinHelper(maxChoosableInteger, desiredTotal - (i + 1), visited | mask, lookup)) {
(*lookup)[visited] = true;
return true;
}
}
mask <<= 1;
}
(*lookup)[visited] = false;
return false;
}
};