Leetcode -- 22. Generate 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:

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

思路:
本题主要应用递归方法:
设s为空,left表示左括号的剩余数,right表示右括号的剩余数,当left>0 时,增加“(”,当right > 0 且 left < right时,增加“)”。以n = 3为例,递归过程如下:

  1. left from 3 to 0, right = 3, s =”(((“;
  2. left = 0, right from 3 to 0, s = “((()))”;
  3. push(s);
  4. left =1, right from 3 to 2, s = “(()”;
  5. left = 0, right from 2 to 0 , s = “(()())”;
  6. push(s);
  7. left = 1, right from 2 to 1, s = “(())”;
  8. left = 0, right from 1 to 0, s = “(())()”;
  9. push(s);
  10. left = 2, right from 3 to 2, s = “()”;
  11. left form 2 to 0, right = 2, s = “()((“;
  12. left = 0, right from 2 to 0, s = “()(())”;
  13. push(s);
  14. left = 1, right from 2 to 1, s = “()()”;
  15. left = 0, right from 1 to 0, s = “()()()”;
  16. push(s);

至此,完成了整个递归过程。代码实现起来比较简单, 如下:

class solution
{
public:
    vector<string> generateParenthesis(int n) 
    {
        vector<string> v;
        generateParenthesis(v, "", n, n);
        return v;
    }

private:
    void generateParenthesis(vector<string> &v, string s, int left, int right)
    {
        if (left == 0 && right == 0)
        {
            v.push_back(s);
        }
        if (left > 0)
        {
            generateParenthesis(v, s + "(", left - 1, right);
        }
        if (right > 0 && left < right)
        {
            generateParenthesis(v, s + ")", left, right - 1);
        }
    }
};

参考:makuiyu的专栏–LeetCode — 22. Generate Parentheses

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值