力扣top100-22. 括号生成-回溯
题目
链接:https://leetcode-cn.com/problems/generate-parentheses
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1
输出:["()"]
算法选择
和电话号盘的题很像,都是直接考虑用递归插入左右括号就行了
只不过栈空间(StringBuilder)里有些值不插入,直接返回(回溯)
思路
设置俩计数器,左右括号的个数
左括号不超过n就可以递归加入左括号
右括号不超过左括号,就递归插入右括号
每次递归完成不要忘记弹出插入的括号
代码
class Solution {
public static List<String> generateParenthesis(int n) {
List<String>res =new ArrayList<>();
StringBuilder sb=new StringBuilder();
int leftCount=0,rightCount=0;//记录左括号-有括号的个数
insertParent(res,sb,leftCount,rightCount,n,0);
return res;
}
pulibc static void insertParent(List<String> res, StringBuilder sb, int leftCount, int rightCount, int n, int i) {
if(i==2*n){
//所有括号都添加了
res.add(sb.toString());
return;
}
//插入第i个左括号
if(leftCount<n){
sb.append("(");
insertParent(res,sb, leftCount+1, rightCount,n,i+1);
sb.deleteCharAt(i);
}
//插入右括号之前要判断
if(rightCount<leftCount) {
sb.append(")");
insertParent(res, sb, leftCount, rightCount + 1, n, i + 1);
sb.deleteCharAt(i);
}
}
}
本文来自博客园,作者:荧惑微光,转载请注明原文链接:https://www.cnblogs.com/yinghuoweiguang/p/15962269.html

浙公网安备 33010602011771号