-
Notifications
You must be signed in to change notification settings - Fork 13
/
Solution022.java
38 lines (32 loc) · 973 Bytes
/
Solution022.java
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 algorithm.leetcode;
import java.util.ArrayList;
import java.util.List;
/**
* @author: mayuan
* @desc: 括号生成
* @date: 2018/07/16
*/
public class Solution022 {
public static void main(String[] args) {
System.out.println(new Solution022().generateParenthesis(3));
}
public List<String> generateParenthesis(int n) {
List<String> ans = new ArrayList<>();
dfs(ans, "", n, 0, 0);
return ans;
}
public void dfs(List<String> ans, String oneAnswer, int n, int left, int right) {
if (right == n) {
ans.add(oneAnswer);
return;
}
// 左括号数量少于 n ,优先添加左括号
if (left < n) {
dfs(ans, oneAnswer + "(", n, left + 1, right);
}
// 右括号数量少于左括号数量 ,添加右括号与左括号配对
if (right < left) {
dfs(ans, oneAnswer + ")", n, left, right + 1);
}
}
}