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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
| class Solution {
public List<String> removeInvalidParentheses(String s) {
StringBuilder sb = new StringBuilder();
Set<String> res = new HashSet<>();
int open = 0;
for (char c: s.toCharArray()) {
if (c == '(') {
open++;
} else if (c == ')') {
if (open > 0) {
open--;
}
}
}
int close = 0;
for (int i = s.length() - 1; i >= 0; i--) {
char c = s.charAt(i);
if (c == '(') {
if (close > 0) {
close--;
}
} else if (c == ')') {
close++;
}
}
// System.out.println(open + " " + close);
backtrack(0, s, 0, open, close, sb, res);
return new ArrayList<>(res);
}
void backtrack(int index, String s,
int openClosed,
int open, int close,
StringBuilder sb, Set<String> res) {
if (open < 0 || close < 0) return;
if (index == s.length()) {
if (open == 0 && close == 0) {
res.add(sb.toString());
}
return;
}
char c = s.charAt(index);
if (c == '(') {
sb.append(c); // add open
backtrack(index + 1, s, openClosed + 1, open, close, sb, res);
sb.deleteCharAt(sb.length() - 1);
// skip open
backtrack(index + 1, s, openClosed, open - 1, close, sb, res);
} else if (c == ')') {
if (openClosed > 0) {
sb.append(c); // add close
backtrack(index + 1, s, openClosed - 1, open, close, sb, res);
sb.deleteCharAt(sb.length() - 1);
}
// skip close
backtrack(index + 1, s, openClosed, open, close - 1, sb, res);
} else {
sb.append(c);
backtrack(index + 1, s, openClosed, open, close, sb, res);
sb.deleteCharAt(sb.length() - 1);
}
}
}
|