forked from TonnyL/Windary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GenerateParentheses.java
55 lines (47 loc) · 1.29 KB
/
GenerateParentheses.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
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.util.*;
/**
* Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
* <p>
* For example, given n = 3, a solution set is:
* <p>
* [
* "((()))",
* "(()())",
* "(())()",
* "()(())",
* "()()()"
* ]
* <p>
* Accepted.
*/
public class GenerateParentheses {
public List<String> generateParenthesis(int n) {
Set<String> set = new HashSet<>();
List<String> list = new ArrayList<>();
if (n <= 0) {
return list;
}
if (n == 1) {
list.add("()");
return list;
}
for (String s : generateParenthesis(n - 1)) {
StringBuilder sb = new StringBuilder();
char[] chars = s.toCharArray();
for (int j = 0; j < chars.length; j++) {
sb.append(chars[j]);
if (chars[j] == '(') {
StringBuilder builder = new StringBuilder(sb);
builder.append("()");
for (int k = j + 1; k < chars.length; k++) {
builder.append(chars[k]);
}
set.add(builder.toString());
}
}
set.add(s + "()");
}
list.addAll(set);
return list;
}
}