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:

"((()))", "(()())", "(())()", "()(())", "()()()"

题目大意:

  给定一个数字n,代表括号的对数,求n对括号匹配的所有情况。

思路:

   拿到题的第一反应想到的是这道题是典型的递归,但是好长时间过去了依然不知道怎么递归。参考学长博客:http://blog.csdn.net/wwh578867817/article/details/46392701,得到规律左半括号永远大于等于右半括号。

代码1:

class Solution {
public:
    std::vector<std::string> generateParenthesis(int n) {
        std::vector<std::string> result;
        
        if (n <= 0) {
            return result;
        }
        std::string s;
        addBrackets(n, n, s, result);
        
        return result;
    }
    
private:
    void addBrackets(int left, int right, std::string s, std::vector<std::string> &result)
    {
        if (left == 0 && right == 0) {
            result.push_back(s);
            return;
        }
        
        if (left == right) {
            addBrackets(left - 1, right, s + "(", result);
        } else {
            if (left > 0) {
                addBrackets(left - 1, right, s + "(", result);
            }
            if (right > 0) {
                addBrackets(left, right - 1, s + ")", result);
            }
        }
    }
};

代码2:

class Solution {
public:
    
    //思想也是保证左半括号个数大于等于右半括号个数
    std::vector<std::string> generateParenthesis(int n) {
        std::string s;
        std::vector<std::string> result;
        generate(n, n, s, result);
        return result;
    }

    void generate(int left, int right, std::string s, std::vector<std::string> &result){
        if(left){
            generate(left - 1, right, s + "(", result); //如果左半括号还没有用完直接加左半括号
            if(left != right){    //如果左右不相等
                generate(left, right - 1, s + ")", result);    //加右半括号
            }
        }else{
            if(right){   //如果还剩右括号没有加入则将剩余的所有右括号都加入
                result.push_back(s + std::string(right,')'));
            }
        }
        return;
    }
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值