首页 > 其他 > 详细

Generate Parentheses

时间:2014-06-04 22:04:23      阅读:351      评论: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:

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

bubuko.com,布布扣
class Solution {
public:
    vector<string> generateParenthesis(int n) {
        string s;
        for(int i=0;i<n*2;i++) s=s+" ";
        
        vector<string> result;
        int left=n;
        int right=n;
        gen(result,s,left,right,0);
        return result;
    }
    void gen(vector<string>& result,string& s,int left,int right,int step)
    {
        if(left>right) return;
        if(left==0 && right==0)
        {
            result.push_back(s);
            return;
        }
        if(left>0)
        {
            s[step]=(;
            gen(result,s,left-1,right,step+1);
        }
        if(right>0)
        {
            s[step]=);
            gen(result,s,left,right-1,step+1);
        }
    }
};
bubuko.com,布布扣

Generate Parentheses,布布扣,bubuko.com

Generate Parentheses

原文:http://www.cnblogs.com/erictanghu/p/3759285.html

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