首页 > 其他 > 详细

Generate Parentheses

时间:2014-03-23 12:34:13      阅读:378      评论: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:

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

思路:这道题给你n对括号,生成所有合法的括号规则。有如下规则:左括号和右括号的数量都为n时,将生成的括号push到result里;左括号的数量小于n,插入str,然后递归;当右括号的数量小于左括号的数量,将‘)‘插入str中,然后递归。

bubuko.com,布布扣
class Solution {
public:
    void MatchNums(int n,vector<string> &result,string &str,int nLeftBrackts,int nRightBrackts)
    {
        if(nLeftBrackts==n&&nRightBrackts==n)
        {
            result.push_back(str);
            return;
        }
        if(nLeftBrackts<n)
        {
            str.push_back(();
            MatchNums(n,result,str,nLeftBrackts+1,nRightBrackts);
            str.pop_back();
        }
        if(nRightBrackts<nLeftBrackts)
        {
            str.push_back());
            MatchNums(n,result,str,nLeftBrackts,nRightBrackts+1);
            str.pop_back();
        }
    }
    vector<string> generateParenthesis(int n) {
        vector<string> result;
        string str;
        MatchNums(n,result,str,0,0);
        return result;
    }
};
bubuko.com,布布扣

Generate Parentheses,布布扣,bubuko.com

Generate Parentheses

原文:http://www.cnblogs.com/awy-blog/p/3618674.html

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