forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path464.Can-I-Win.cpp
32 lines (29 loc) · 929 Bytes
/
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
class Solution {
int visited[1<<21];
public:
bool canIWin(int maxChoosableInteger, int desiredTotal)
{
int totalSum = (1+maxChoosableInteger)*maxChoosableInteger/2;
if (totalSum < desiredTotal) return false;
return dfs(0, 0, maxChoosableInteger, desiredTotal);
}
bool dfs(int state, int sum, int maxChoosableInteger, int desiredTotal)
{
if (visited[state]==2)
return true;
if (visited[state]==1)
return false;
for (int i=1; i<=maxChoosableInteger; i++)
{
if ((state>>i)&1) continue;
if (sum+i >= desiredTotal) return true;
if (dfs(state+(1<<i), sum+i, maxChoosableInteger, desiredTotal)==false)
{
visited[state] = 2;
return true;
}
}
visited[state] = 1;
return false;
}
};