22. Generate Parentheses -Meidum

Question

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

给出一对括号,请你生成所有良好格式的组合(每个开括号后总有一个闭括号对应,错误示例:“)(”)

Example

given n = 3, a solution set is:

[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]

Solution

  • 回溯解。这道题如果是求由n对括号组成的所有形式,那么这和之前的PermutationsII一样,只需要生成如{“(“, “(“, “(“, “)”, “)”, “)”},然后进行回溯,其中排除重复元素即可。但是这里有一个额外的要求就是开括号后面必须有对应的闭括号,所以上面的思路不可行。我们的思路是只要出现开括号,我们也要添加闭括号以保证括号成对出现

    // 当开括号未达到n时添加开括号
    if(open < max){
        backtracking(open + 1, close, max, res, temp + "(");
    }
    // 对每一个开括号确保有相应的闭括号对应
    if(close < open){
        backtracking(open, close + 1, max, res, temp + ")");
    }

    所以只要当保存的string字符串的元素个数为n * 2(因为n代表一对括号),该字符串就是我们所需的结果

    public class Solution {
        public List<String> generateParenthesis(int n) {
            List<String> res = new ArrayList<>();
            backtracking(0, 0, n, res, "");
            return res;
        }
    
        public void backtracking(int open, int close, int max, List<String> res, String temp){
            if(temp.length() == max * 2){
                res.add(temp);
                return;
            }
    
            // 当开括号未达到max时添加开括号
            if(open < max){
                backtracking(open + 1, close, max, res, temp + "(");
            }
            // 对每一个开括号确保有相应的闭括号对应
            if(close < open){
                backtracking(open, close + 1, max, res, temp + ")");
            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值