算法通关村——回溯模板如何解决括号生成问题

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);            
        }
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值