-
Notifications
You must be signed in to change notification settings - Fork 0
/
GenerateParentheses.java
43 lines (35 loc) · 1.16 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
/*
* Re-do this question, now dfsWorker() return void
*/
public class Solution {
public ArrayList<String> generateParenthesis(int n) {
ArrayList<String> result = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
if(n <= 0)
return result;
dfsWorker(n, result, sb, 0, 0);
return result;
}
public void dfsWorker(int n, ArrayList<String> result, StringBuilder sb, int left, int right){
//"exit" for recursive call
if(left == right && right == n){
result.add(sb.toString());
return;
}
//invalid combination
if(left < right || left > n || right > n)
return;
//condition that add '('
if(left < n){
sb.append('(');
dfsWorker(n, result, sb, left+1, right);
sb.deleteCharAt(sb.length()-1);
}
//condition that add ')'
if(right < left){
sb.append(')');
dfsWorker(n, result, sb, left, right+1);
sb.deleteCharAt(sb.length()-1);
}
}
}