LeetCode22.数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
根据例子我们可以知道“(”是一定先出现的,而“)”只要“(”出现一次就可以开始添加到集合里去,
那停止回溯的条件就很简单了,当所有括号都添加到集合里的时候就停止回溯。也就是集合的长度等于2n。
那么代码就很容易写出来了,代码如下
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
backtrack(res, new StringBuilder(), 0, 0, n);
return res;
}
/**
* @param res 最后保存的结果
* @param temp 当前的括号串
* @param left 左括号已经使用的个数
* @param right 右括号已经使用的个数
* @param n 序列长度最大值
*/
public void backtrack(List<String> res, StringBuilder temp, int left, int right, int n){
if(temp.length() == n*2){
res.add(temp.toString());
return ;
}
if(left < n){
temp.append("(");
backtrack(res, temp, left + 1, right, n);
temp.deleteCharAt(temp.length() - 1);
}
if(right < left){
temp.append(")");
backtrack(res, temp, left, right + 1, n);
temp.deleteCharAt(temp.length() - 1);
}
}
}
863

被折叠的 条评论
为什么被折叠?



