[LeetCode - 回溯] 22. Generate Parentheses

1 题目

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

2 分析

题目要生成所有特定长度的有效括号组合,可以发现,该问题可以分解为多个子问题,即长度为n的括号组合可以由长度为n-1的括号组合生成。因此可以使用递归方法解体,递归树如下图所示:

递归树

在递归的过程中,如果出现下面两种情况,则说明以该节点为顶点的子树中一定不会存在有效的括号组合:

  • 左括号的数目大于n
  • 出现了单独的右括号

此时回溯。当节点的长度为2n时候,即为题目所求的括号有效组合。

3 代码

public class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<>();
        helper(result, "(", n);
        return result;
    }


    private void helper(List<String> res, String str, int n){
        if(!isValid(str,n)){
            return;
        }
        if(str.length() == 2*n){
            res.add(str);
            return;
        }
        helper(res, str + "(", n);
        helper(res, str + ")", n);
    }


    private boolean isValid(String str, int n){
        LinkedList<String> stack = new LinkedList<>();
        int numOfLeftPa = 0;
        for(int i = 0; i < str.length(); i++){
            if(str.charAt(i) == '('){
                if(numOfLeftPa >= n){
                    return false;
                }
                stack.push("(");
                numOfLeftPa++;
            }else{
                if(stack.size() == 0){
                    return false;
                }
                stack.pop();
            }
        }
        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值