forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path464.Can-I-Win.cpp
47 lines (42 loc) · 1.2 KB
/
464.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
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
int maxChoosableInteger;
int desiredTotal;
unordered_map<int,bool>Map;
public:
bool canIWin(int maxChoosableInteger, int desiredTotal)
{
if (desiredTotal==0) return true;
if (desiredTotal > (1+maxChoosableInteger)*maxChoosableInteger/2)
return false;
this->maxChoosableInteger = maxChoosableInteger;
this->desiredTotal = desiredTotal;
return DFS(0);
}
bool DFS(int status)
{
if (Map.find(status)!=Map.end()) return Map[status];
int sum = 0;
for (int i=1; i<=maxChoosableInteger; i++)
{
if (((status>>i)&1)==1)
sum+=(i);
}
if (sum>=desiredTotal)
{
Map[status] = false;
return false;
}
for (int i=1; i<=maxChoosableInteger; i++)
{
if (((status>>i)&1)==1) continue;
int newStatus = status | (1<<i);
if (DFS(newStatus)==false)
{
Map[status] = true;
return true;
}
}
Map[status] = false;
return false;
}
};