leetcode-22. Generate Parentheses

题目类型:

回溯法,递归

题意:

给出一个整数n,表示有n组括号,输出所有正确的括号组合。

例子:

输入3,

leetcode22

我的思路:回溯+递归

递归一:以==剩余==未添加的左右括号数目为判断条件

50%

递归函数:传递string

  1. 对于这道题,第一个肯定是’(‘,接下来即可以是’(‘也可以是’)’
    • left:表示==剩余==左括号的数目
    • right:表示==剩余==右括号的数目
  2. 需要满足以下规则:
    1. 当left=0&&right=0时表示找到一条路径,加入res
    2. 当left!=0时可以向左子树伸展
    3. 当right!=0&&left< right时可以向右子树伸展
  3. 进行深度搜索。

示意图

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        helper("", n, n, res);
        return res;
    }
    private void helper(String path, int left, int right, List<String> res) {//path代表当前的字符串,left代表剩余未加入path的左括号数目,right表示未加入path的右括号数目
        if (left == 0 && right == 0) {
            res.add(path);
            return;
        }
        if (left != 0) {
            helper(path + "(", left - 1, right, res);
        }
        if (right != 0 && left < right) {//只有path中左括号多余右括号(即剩余左括号少于右括号)时,才能添加右括号(注意:任何时刻剩余左括号数目一定少于等于剩余右括号数目)
            helper(path + ")", left, right - 1, res);
        }
        //其他情况,例如left==0但right!=0,right==0但left!=0,right!=0但left>right,都是非法的
    }
}

递归方法二:以==已经被使用==的左右括号数目为判断条件

81%

递归函数传递参数:已经被使用的左右括号数目,n
1. 对于传入的字符串,如果长度为2*n,那么加入res,否则:
2. 如果被使用的左括号数目小于n,那么加左括号,left+1,字符串拼接(,继续递归
3. 如果被使用的右括号数目小于左括号数目,那么right+1,字符串拼接),继续递归

class Solution {
    //递归方法二:
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        helper("", 0, 0, n, res);
        return res;
    }

    private void helper(String path, int left, int right, int n, List<String> res) {
        if (path.length() == 2 * n) {
            res.add(path);
            return;
        }
        if (left < n) {
            helper(path + "(", left + 1, right, n, res);
        }
        if (right < left) {
            helper(path + ")", left, right + 1, n, res);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值