首页 > 其他 > 详细

LeetCode 022 Generate Parentheses

时间:2015-02-07 17:22:13      阅读:150      评论:0      收藏:0      [点我收藏+]

题目描述:Generate Parentheses

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:

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

 

分析:

递归

 

代码如下:

class Solution {
private:
    vector<string> ret;
public:
    void solve(int dep, int maxDep, int leftNum, int leftNumTotal, string s)
    {
        //如果(个数超出,return
        if (leftNumTotal * 2 > maxDep)
            return;
            
        //如果长度足够,return    
        if (dep == maxDep){
            ret.push_back(s);
            return;
        }
        
        for(int i = 0; i < 2; i++)
        
            //加 (
            if (i == 0)
                solve(dep + 1, maxDep, leftNum + 1, leftNumTotal + 1, s + ();
            //加 )
            else if (leftNum > 0)
                solve(dep + 1, maxDep, leftNum - 1, leftNumTotal, s + ));
    }
    
    vector<string> generateParenthesis(int n){
        ret.clear();
        solve(0, 2 * n, 0, 0, "");
        return ret;
    }
};

 

LeetCode 022 Generate Parentheses

原文:http://www.cnblogs.com/510602159-Yano/p/4278943.html

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