-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlipGameII.java
More file actions
50 lines (37 loc) · 1.19 KB
/
FlipGameII.java
File metadata and controls
50 lines (37 loc) · 1.19 KB
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
import java.util.HashMap;
import java.util.Map;
public class FlipGameII {
/**
AmazonDebug 1:
Recursion
T(N) = (N - 1) * T(N - 2) = (N - 1) * (N - 3) * T(N - 4) = (N - 1) !
canWin("++++++") = !canWin("--++++") || !canWin("+--+++") || !canWin("++--++") || !canWin("+++--+") || !canWin("++++--")
AmazonDebug 2:
Recursion + memoriztion
*/
public boolean canWin(String s) {
return canWinHelper(s.toCharArray(), new HashMap<>());
}
public boolean canWinHelper(char[] chars, Map<char[], Boolean> map) {
if(map.get(chars) != null) {
return map.get(chars);
}
boolean res = false;
for(int i = 0; i < chars.length - 1; i++) {
if(chars[i] == '+' && chars[i + 1] =='+') {
chars[i] = '-';
chars[i + 1] = '-';
res = res || !canWinHelper(chars, map);
chars[i] = '+';
chars[i + 1] = '+';
}
}
map.put(chars.clone(), res);
return res;
}
public static void main(String[] args) {
String input = "++++";
FlipGameII a = new FlipGameII();
a.canWin(input);
}
}