首页 > 其他 > 详细

求n组括号的排列方式 --- 卡特拉数

时间:2014-09-04 22:17:00      阅读:355      评论: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:

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

 

void generate(int n, int nLeft, int nRight, string strVal, vector<string> &resVec)
{
    if (nLeft < nRight)
        return;
    if (nLeft==n && nRight==n)
        resVec.push_back(strVal);

    if (nLeft < n)
        generate(n, nLeft+1, nRight, strVal+"(", resVec);
    if (nLeft > nRight)
        generate(n, nLeft, nRight+1, strVal+")", resVec);
}
  
    vector<string> generateParenthesis(int n) {
        vector<string> ans;
        if (n < 1)
            return ans;

        generate(n, 0, 0, "", ans);

        return ans; 
    }

 

求n组括号的排列方式 --- 卡特拉数

原文:http://www.cnblogs.com/zhhwgis/p/3956903.html

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