-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathGenerateParentheses.java
More file actions
32 lines (28 loc) · 889 Bytes
/
GenerateParentheses.java
File metadata and controls
32 lines (28 loc) · 889 Bytes
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
class Solution {
public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<String>();
// mutable
backtrackHelper(list, new StringBuilder(), 0, 0, n);
return list;
}
public void backtrackHelper(List<String> list, StringBuilder str, int open, int closed, int n){
// aborting condition
if(closed>open){
return ;
}
if(closed == open && str.length() == n*2 ) {
list.add(str.toString());
return;
}
if(open < n) {
str.append("(");
backtrackHelper(list, str, open+1, closed, n);
str.deleteCharAt(str.length()-1);;
}
if(closed < open) {
str.append(")");
backtrackHelper(list, str, open, closed+1, n);
str.deleteCharAt(str.length()-1);;
}
}
}