Skip to content

Commit a742036

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 22_Generate_Parentheses.java
1 parent 089d568 commit a742036

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public List<String> generateParenthesis(int n) {
3+
if (n <= 0) {
4+
return Collections.emptyList();
5+
}
6+
7+
List<String> result = new ArrayList<>();
8+
dfs(n, 0, 0, new StringBuilder(), result);
9+
return result;
10+
}
11+
12+
private void dfs(int n, int open, int close, StringBuilder sb, List<String> result) {
13+
if (open == n && close == n) {
14+
result.add(sb.toString());
15+
return;
16+
}
17+
18+
if (open < n) {
19+
sb.append('(');
20+
dfs(n, open + 1, close, sb, result);
21+
sb.deleteCharAt(sb.length() - 1);
22+
}
23+
24+
if (close < open) {
25+
sb.append(')');
26+
dfs(n, open, close + 1, sb, result);
27+
sb.deleteCharAt(sb.length() - 1);
28+
}
29+
}
30+
}

0 commit comments

Comments
 (0)