Skip to content

Commit fd5a9e3

Browse files
authored
Create 022. Generate Parentheses.java
1 parent 5050f43 commit fd5a9e3

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

022. Generate Parentheses.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
public class Solution {
2+
public void helper(List<String> result, int n, String sofar, int left, int right) {
3+
if (sofar.length() == n*2) {
4+
result.add(sofar);
5+
return;
6+
}
7+
8+
if (left == right) {
9+
helper(result, n, sofar + "(", left + 1, right);
10+
} else if (left > right && left < n) {
11+
helper(result, n, sofar + "(", left + 1, right);
12+
helper(result, n, sofar + ")", left, right + 1);
13+
} else {
14+
helper(result, n, sofar + ")", left, right + 1);
15+
}
16+
}
17+
public List<String> generateParenthesis(int n) {
18+
List<String> out = new ArrayList<String>();
19+
helper(out, n, "", 0, 0);
20+
21+
return out;
22+
}
23+
}

0 commit comments

Comments
 (0)