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

LeetCode 022 Generate Parentheses

时间:2015-02-07 17:25:12      阅读:128      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!