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

22.Generate Parentheses (String; dfs)

时间:2015-08-05 19:54:01      阅读:103      评论: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:

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

思路:两个dfs函数,互相调用

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        if(n == 0) return ret;
        
        len = n*2;
        dfsLeft(n, 0, "");
        return ret;
    }
    
    void dfsRight(int lNum, int rNum, string str){//add right parenthese
        while(rNum){ 
            str += );
            dfsLeft(lNum, --rNum, str);
        }
        if(str.length() == len){
            ret.push_back(str);
        }
    }
    
    void dfsLeft(int lNum, int rNum, string str){//add left parenthese
        while(lNum){
            str += (;
            dfsRight(--lNum, ++rNum, str);
        }
    }
private:
    int len;
    vector<string> ret;

};

 

22.Generate Parentheses (String; dfs)

标签:

原文地址:http://www.cnblogs.com/qionglouyuyu/p/4705551.html

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