数字 n
代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的
括号
组合。
输入:n = 3输出:[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
非回溯法:
放到参数中,每次新建字符串
import org.w3c.dom.html.HTMLHeadElement;
import java.util.*;
class Solution {
public List<String> generateParenthesis(int n) {
return dfs(n, n, "");
}
private List<String> dfs(int left, int right, String s) {
List<String> res = new ArrayList<>();
if (left == 0 && right == 0) {
res.add(s);
}
if (left > 0)
res.addAll(dfs(left - 1, right, s + "("));
if (right > left)
res.addAll(dfs(left, right - 1, s + ")"));
return res;
}
public static void main(String[] args) {
System.out.println(new Solution().generateParenthesis(4));
}
}
回溯法:
import java.util.*;
class Solution {
public List<String> generateParenthesis(int n) {
StringBuilder sb = new StringBuilder();
return dfs(n, n, sb);
}
private List<String> dfs(int left, int right, StringBuilder sb) {
List<String> res = new ArrayList<>();
if (left == 0 && right == 0) {
res.add(sb.toString());
return res;
}
if (left > 0) {
res.addAll(dfs(left - 1, right, sb.append("(")));
sb.deleteCharAt(sb.length() - 1);//回溯,删除上次加的字符
}
if (right > left) {
res.addAll(dfs(left, right - 1, sb.append(")")));
sb.deleteCharAt(sb.length() - 1);//回溯,删除上次加的字符
}
return res;
}
public static void main(String[] args) {
System.out.println(new Solution().generateParenthesis(4));
}
}