-
Notifications
You must be signed in to change notification settings - Fork 7
/
can-I-win.java
42 lines (40 loc) · 1.27 KB
/
can-I-win.java
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
import java.util.*;
public class Solution {
HashMap<Integer, Boolean> hm;
boolean[] used;
public boolean canIWin(int maxChoosableInteger, int desiredTotal) {
int sum = (maxChoosableInteger+1) * maxChoosableInteger / 2;
if (sum < desiredTotal) return false;
if (desiredTotal <= 0) return true;
hm = new HashMap<Integer, Boolean>();
used = new boolean[maxChoosableInteger+1];
return canFirstWin(desiredTotal);
}
public boolean canWin(int total) {
if (total <= 0) return false;
int usedArray = format(used);
if (!hm.containsKey(usedArray)) {
for (int i = 1; i <= used.length; i++) {
if (!used[i]) {
used[i] = true;
if (!canWin(total - i)) {
hm.put(usedArray, true);
used[i] = false;
return true;
}
used[i] = false;
}
}
hm.put(key, false);
}
return false;
}
public int binaryToInteger(boolean[] used) {
int retVal = 0;
for (boolean i : used) {
retVal <<= 1;
if (i) retVal |= 1;
}
return retVal;
}
}