-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathGenerateParentheses.java
49 lines (42 loc) · 1.39 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
/*
* Given n pairs of parentheses, write a function to
* generate all combinations of well-formed parentheses.
Example
Given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
*/
public class GenerateParentheses {
public ArrayList<String> generateParenthesis(int n) {
ArrayList<String> result = new ArrayList<String>();
dfs(result, "", n, n);
return result;
}
public void dfs(ArrayList<String> result, String s, int left, int right) {
if (left < 0 || left > right) {
return;
}
if (left == 0 && right == 0) {
result.add(s);
}
dfs(result, s + "(", left - 1, right);
dfs(result, s + ")", left, right - 1);
}
/*****************************************************************************/
public ArrayList<String> generateParenthesis(int n) {
ArrayList<String> result = new ArrayList<String>();
if (n == 0) {
result.add("");
} else if (n == 1) {
result.add("()");
} else if (n > 1) {
for (int i = 0; i < n; ++i) {
for (String inner : generateParenthesis(i)) {
for (String outer : generateParenthesis(n - i - 1)) {
result.add("(" + inner + ")" + outer);
}
}
}
}
return result;
}
}