-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathSolution.java
More file actions
38 lines (35 loc) · 854 Bytes
/
Solution.java
File metadata and controls
38 lines (35 loc) · 854 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
29
30
31
32
33
34
35
36
37
38
package GenerateParentheses;
import java.util.ArrayList;
import java.util.List;
/**
* User: Danyang
* Date: 1/17/2015
* Time: 16:29
*/
public class Solution {
/**
* Notice:
* 1. reference to save space
* @param n
* @return
*/
public List<String> generateParenthesis(int n) {
List<String> ret = new ArrayList<>();
dfs(n, 0, 0, new StringBuilder(), ret);
return ret;
}
public void dfs(int n, int l, int r, StringBuilder cur, List<String> ret) {
if(r==n&&l==n) {
ret.add(cur.toString());
return ;
}
if(l+1<=n) {
dfs(n, l+1, r, cur.append("("), ret);
cur.delete(l+r, l+r+1);
}
if(l<=n && r<l) {
dfs(n, l, r+1, cur.append(")"), ret);
cur.delete(l+r, l+r+1);
}
}
}