Skip to content

Commit 20351e8

Browse files
authored
Merge pull request doocs#88 from bluesword12350/master
022. Generate Parentheses (java)
2 parents 25c8cb8 + b6b8b34 commit 20351e8

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
List<String> result = new ArrayList<>();
3+
public List<String> generateParenthesis(int n) {
4+
generateParenthesis(n, n, new char[n * 2], 0);
5+
return result;
6+
}
7+
void generateParenthesis(int left, int right, char[] cache, int index) {
8+
if (right == 0) {
9+
result.add(String.valueOf(cache));
10+
return;
11+
}
12+
if (left > 0) {
13+
cache[index] = '(';
14+
generateParenthesis(left - 1, right, cache, index + 1);
15+
}
16+
if (right > left) {
17+
cache[index] = ')';
18+
generateParenthesis(left, right - 1, cache, index + 1);
19+
}
20+
}
21+
}

0 commit comments

Comments
 (0)