-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
43 lines (35 loc) · 1.11 KB
/
Copy pathSolution.java
File metadata and controls
43 lines (35 loc) · 1.11 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
package generateParentheses;
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> results = new ArrayList<String>();
if (n != 0)
genParen(results, n, n, new StringBuilder());
return results;
}
public void genParen(List<String> results, int left, int right, StringBuilder tmp) {
if (right == 0) {
results.add(tmp.toString());
return;
} else {
if (left > 0) {
tmp.append("(");
genParen(results, left - 1, right, tmp);
tmp.deleteCharAt(tmp.length()-1);
}
if (left < right) {
tmp.append(")");
genParen(results, left, right - 1, tmp);
tmp.deleteCharAt(tmp.length()-1);
}
}
}
public static void main(String[] args) {
int n = 2;
List<String> results = new Solution().generateParenthesis(n);
for (String result : results) {
System.out.println(result);
}
}
}