forked from yuduozhou/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathGenerateParentheses.java
More file actions
28 lines (24 loc) · 838 Bytes
/
GenerateParentheses.java
File metadata and controls
28 lines (24 loc) · 838 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class Solution {
public ArrayList<String> generateParenthesis(int n) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<String> result = new ArrayList<String>();
char[] parens = new char[n+n];
gp (result, 0, 0, n, parens);
return result;
}
public void gp(ArrayList<String> result, int left, int right, int n, char[] parens) {
if (left == right && left == n) {
result.add(new String(parens));
return;
}
if (left < n) {
parens[left + right] = '(';
gp(result, left + 1, right, n, parens);
}
if (right < left) {
parens[left + right] = ')';
gp(result, left, right + 1, n, parens);
}
}
}