-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcan-i-win.cpp
60 lines (51 loc) · 914 Bytes
/
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
48
49
50
51
52
53
54
55
56
57
58
59
60
//Runtime: 183 ms
class Solution {
public:
unordered_map<int, bool> Mp;
vector<bool>used;
int findkey(vector<bool>&used)
{
int num = 0;
for (bool a : used)
{
num <<= 1;
if (a) num |= 1;
}
return num;
}
bool solve(int dt)
{
if (dt <= 0)
return 0;
int key = findkey(used);
auto it = Mp.find(key);
if (it != Mp.end())
return it->second;
for (int i = 1; i < used.size(); i++)
{
if (!used[i])
{
used[i] = 1;
if (!solve(dt - i))
{
Mp[key] = 1;
used[i] = 0;
return 1;
}
used[i] = 0;
}
}
Mp[key] = 0;
return 0;
}
bool canIWin(int maxChoosableInteger, int desiredTotal) {
if (desiredTotal <= 0)
return 1;
int sum = (1 + maxChoosableInteger) * maxChoosableInteger / 2;
if (sum < desiredTotal)
return 0;
for (int i = 0; i <= maxChoosableInteger; i++)
used.push_back(0);
return solve(desiredTotal);
}
};