LC22 General Parentheses 回溯/递归 生产所有有效的括号对

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:

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

LeetCode括号系列之一,难度一般,很直接的想到使用回溯

回溯从左往右生成一个新的组合的时候,判断条件是通过判断left和right两个指标。举例说明,numbers of pairs, which is n, equals to 3,其中left表示剩下的可用的做括号数;同理right表示剩余的右括号数。观察从左往右生成新组合的过程,什么情况下当前组合是valid?答案是:只要left小于等于right都是有效的,其中当left==right==0时说明已经没有括号剩余,当前组合可以加入到给目标数组。这道题只要意识到上面的observation就没有任何难度了。代码如下:

void getParanthesis(vector<string>& ans, string curr, int left, int right) {
    //left: number of remaining '('
    //right: number of remaining ')'
    if (left > right) {
        return;
    }
    if (left == 0 && right == 0) {
        ans.push_back(curr);
    }
    else {
        if (left > 0) {
            getParanthesis(ans, curr + "(", left - 1, right);
        }
        if(right > 0) {
            getParanthesis(ans, curr + ")", left, right -1);
        }
    }
}
vector<string> generateParenthesis(int n) {
    vector<string> ans;
    getParanthesis(ans, "", n, n);
    return ans;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值