题目链接
法一(dfs)
public class Solution22 {
private List<String> ans;
public Solution22() {
this.ans = new LinkedList<>();
}
private void dfs(int left, int right, String curStr) {
if (left > right || left < 0 || right < 0) {
return;
}
if (left == 0 && right == 0) {
ans.add(curStr);
return;
}
dfs(left - 1, right, curStr + "(");
dfs(left, right - 1, curStr + ")");
}
public List<String> generateParenthesis(int n) {
dfs(n, n, "");
return ans;
}
}
- 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
法二(回溯)
public class Solution22 {
private List<String> ans;
public Solution22() {
this.ans = new LinkedList<>();
}
private void backtracking(int left, int right, StringBuilder curStr) {
if (left == 0 && right == 0) {
ans.add(curStr.toString());
return;
}
if (left > 0) {
curStr.append("(");
backtracking(left - 1, right, curStr);
curStr.deleteCharAt(curStr.length() - 1);
}
if (left < right) {
curStr.append(")");
backtracking(left, right - 1, curStr);
curStr.deleteCharAt(curStr.length() - 1);
}
}
public List<String> generateParenthesis_2(int n) {
backtracking(n, n, new StringBuilder());
return ans;
}
}
- 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
- 39
- 40
- 41
- 42
- 43
本地测试
lay.showTitle(22);
Solution22 sol22_1 = new Solution22();
List<String> ans22_1 = sol22_1.generateParenthesis(3);
arrayOpt.showStringList(ans22_1);
Solution22 sol22_2 = new Solution22();
List<String> ans22_2 = sol22_2.generateParenthesis_2(3);
arrayOpt.showStringList(ans22_2);