首页 > 其他 > 详细

leetcode22. Generate Parentheses

时间:2016-02-13 23:11:48      阅读:395      评论:0      收藏:0      [点我收藏+]

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:

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

这个问题解的个数为卡特兰数。不过这道题并不是求解的个数,而是将所有合法括号打印出来。

设leftnum和rightnum为左右括号的剩余量,则leftnum>0时可以继续打印"(",当rightnum>leftnum时可以打印")"。

class Solution {
public:
    void generate(int leftnum,int rightnum,string s,vector<string>& res)
    {
        if(leftnum==0 && rightnum==0)
            res.push_back(s);
        if(leftnum>0)
            generate(leftnum-1,rightnum,s+"(",res);
        if(rightnum>leftnum && rightnum>0)
            generate(leftnum,rightnum-1,s+")",res);
    }
    vector<string> generateParenthesis(int n) {
        vector<string> strs;
        generate(n,n,"",strs);
        return strs;
    }
    
};

 

leetcode22. Generate Parentheses

原文:http://www.cnblogs.com/tonychen-tobeTopCoder/p/5188353.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!