-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenerateParentheses.java
More file actions
37 lines (32 loc) · 1.02 KB
/
Copy pathGenerateParentheses.java
File metadata and controls
37 lines (32 loc) · 1.02 KB
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
29
30
31
32
33
34
35
36
37
class Solution {
public List<String> generateParenthesis(int n) {
if(n < 0) throw new IllegalArgumentException("xx");
if(n == 0) return Collections.emptyList();
List<String> result = new ArrayList<>();
gph(result, "", 0, 0, n);
return result;
}
private void gph(List<String> result, String sofar, int l , int r, int n) {
if(sofar.length() == 2*n) {
result.add(sofar);
return;
}
if(l < n) gph(result, sofar+"(", l+1, r, n);
if(l > r) gph(result, sofar+")", l, r+1, n);
}
}
class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
gph(result, "", n, n);
return result;
}
private void gph(List<String> result, String sofar, int l, int r) {
if (r == 0) {
result.add(sofar);
return;
}
if(l > 0) gph(result, sofar+"(", l-1, r);
if(l < r) gph(result, sofar+")", l, r-1);
}
}