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

Generate Parentheses

时间:2015-03-20 23:21:33      阅读:248      评论: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: 

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

  这题没做出来,惭愧。

solution:

void dfs(vector<string> &result,string str,int left,int right)
{
    if(left > right)
        return;
    if (left == 0 && right == 0)
    {
        result.push_back(str);
        return;
    }
    if(left > 0)
        dfs(result, str+"(", left-1, right);
    if(right > 0)
        dfs(result, str+")", left, right-1);
}

vector<string> generateParenthesis(int n) {
    vector<string> res;
    if(n < 1) 
        return res;
    dfs(res, "", n, n);
    return res;
}

原文链接:http://blog.csdn.net/linhuanmars/article/details/19873463

Generate Parentheses

标签:

原文地址:http://www.cnblogs.com/gattaca/p/4354700.html

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