-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathGenerateParentheses.java
More file actions
38 lines (36 loc) · 1.27 KB
/
GenerateParentheses.java
File metadata and controls
38 lines (36 loc) · 1.27 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
package com.dbc;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GenerateParentheses {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<String>(){{
add("()");
}};
if (n == 1) return res;
for (int i = 1; i < n; i++) {
Map<String, Boolean> remain = new HashMap<>();
List<String> tempRes = new ArrayList<>();
for (String item : res) {
if (remain.getOrDefault("()" + item, true)) {
tempRes.add("()" + item);
remain.put("()" + item, false);
}
if (remain.getOrDefault(item + "()", true)) {
tempRes.add(item + "()");
remain.put(item + "()", false);
}
for (int j = 1; j < item.length(); j++) {
String comStr = item.substring(0, j) + "()" + item.substring(j, item.length());
if (remain.getOrDefault(comStr, true)) {
tempRes.add(comStr);
remain.put(comStr, false);
}
}
}
res = tempRes;
}
return res;
}
}