Skip to content

Commit ea5b95b

Browse files
authored
Create week6 464. Can I Win
1 parent 3bfa4ae commit ea5b95b

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

week6 464. Can I Win

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
public class Solution {
2+
public boolean canIWin(int maxChoosableInteger, int desiredTotal) {
3+
if (desiredTotal <= 0){
4+
return true;
5+
}
6+
if (maxChoosableInteger * (maxChoosableInteger + 1) / 2 < desiredTotal){
7+
return false;
8+
}
9+
return canIWin(desiredTotal, maxChoosableInteger, 0, new HashMap<>());
10+
}
11+
private boolean canIWin(int total, int n, int state, HashMap<Integer,Boolean>cache)
12+
if(total <= 0){
13+
return false;
14+
}
15+
if (cache.containsKey(state)){
16+
return cache.get(state);
17+
}
18+
19+
for(int i = 0; i < n; i++){
20+
if((state & (1 << i)) != 0){
21+
continue;
22+
}
23+
if (!canIWin(total-(i+1), n, state | (1<<i), cache)){
24+
cache.put(state, ture);
25+
return true;
26+
}
27+
}
28+
29+
cache.put(state, false);
30+
return false;
31+
}

0 commit comments

Comments
 (0)