码迷,mamicode.com
首页 > 其他好文 > 详细

Generate Parentheses

时间:2014-06-04 22:30:30      阅读:418      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

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

标签:c   style   class   blog   code   java   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!