-
Notifications
You must be signed in to change notification settings - Fork 4
/
CanIWin.java
35 lines (31 loc) · 1.17 KB
/
CanIWin.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
package com.dbc;
import java.util.HashMap;
import java.util.Map;
public class CanIWin {
Map<Integer, Boolean> memo = new HashMap<Integer, Boolean>();
public boolean canIWin(int maxChoosableInteger, int desiredTotal) {
if ((1 + maxChoosableInteger) * (maxChoosableInteger) / 2 < desiredTotal) {
return false;
}
return dfs(maxChoosableInteger, 0, desiredTotal, 0);
}
public boolean dfs(int maxChoosableInteger, int usedNumbers, int desiredTotal, int currentTotal) {
if (!memo.containsKey(usedNumbers)) {
boolean res = false;
for (int i = 0; i < maxChoosableInteger; i++) {
if (((usedNumbers >> i) & 1) == 0) {
if (i + 1 + currentTotal >= desiredTotal) {
res = true;
break;
}
if (!dfs(maxChoosableInteger, usedNumbers | (1 << i), desiredTotal, currentTotal + i + 1)) {
res = true;
break;
}
}
}
memo.put(usedNumbers, res);
}
return memo.get(usedNumbers);
}
}