Skip to content

Commit be78f12

Browse files
committedFeb 18, 2020
Update Solution.java to problems 22
1 parent 59479e8 commit be78f12

File tree

1 file changed

+11
-12
lines changed

1 file changed

+11
-12
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,20 @@
11
class Solution {
2-
List<String> result = new ArrayList<>();
32
public List<String> generateParenthesis(int n) {
4-
generateParenthesis(n, n, new char[n * 2], 0);
5-
return result;
3+
List<String> res = new ArrayList<>();
4+
dfs(res, "", 0, 0, n);
5+
return res;
66
}
7-
void generateParenthesis(int left, int right, char[] cache, int index) {
8-
if (right == 0) {
9-
result.add(String.valueOf(cache));
7+
8+
private void dfs(List<String> res, String ans, int l, int r, int length) {
9+
if (ans.length() == length * 2) {
10+
res.add(ans);
1011
return;
1112
}
12-
if (left > 0) {
13-
cache[index] = '(';
14-
generateParenthesis(left - 1, right, cache, index + 1);
13+
if (l < length) {
14+
dfs(res, ans + "(", l + 1, r, length);
1515
}
16-
if (right > left) {
17-
cache[index] = ')';
18-
generateParenthesis(left, right - 1, cache, index + 1);
16+
if (r < l) {
17+
dfs(res, ans + ")", l, r + 1, length);
1918
}
2019
}
2120
}

0 commit comments

Comments
 (0)
Please sign in to comment.