首页 > 其他 > 详细

22.Generate Parentheses (String; dfs)

时间:2015-08-05 19:50:55      阅读:263      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!