Skip to content

Commit cbd7c15

Browse files
Sean PrashadSean Prashad
authored andcommitted
Update 22_Generate_Parentheses.java
1 parent 21f111b commit cbd7c15

File tree

1 file changed

+11
-14
lines changed

1 file changed

+11
-14
lines changed
Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,27 @@
11
class Solution {
22
public List<String> generateParenthesis(int n) {
3-
if (n <= 0) {
4-
return Collections.emptyList();
5-
}
6-
73
List<String> result = new ArrayList<>();
8-
dfs(n, 0, 0, new StringBuilder(), result);
4+
5+
helper(n, 0, 0, new StringBuilder(), result);
96
return result;
107
}
118

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());
9+
private void helper(int n, int open, int close, StringBuilder temp, List<String> result) {
10+
if (temp.length() == n * 2) {
11+
result.add(temp.toString());
1512
return;
1613
}
1714

1815
if (open < n) {
19-
sb.append('(');
20-
dfs(n, open + 1, close, sb, result);
21-
sb.deleteCharAt(sb.length() - 1);
16+
temp.append("(");
17+
helper(n, open + 1, close, temp, result);
18+
temp.deleteCharAt(temp.length() - 1);
2219
}
2320

2421
if (close < open) {
25-
sb.append(')');
26-
dfs(n, open, close + 1, sb, result);
27-
sb.deleteCharAt(sb.length() - 1);
22+
temp.append(")");
23+
helper(n, open, close + 1, temp, result);
24+
temp.deleteCharAt(temp.length() - 1);
2825
}
2926
}
3027
}

0 commit comments

Comments
 (0)