标签:
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:
“((()))”, “(()())”, “(())()”, “()(())”, “()()()”
如果这道题是求上面括号的组合有多少种方式,那么这是一道卡塔兰数的题目,最开始就陷入到这里了,按照卡塔兰数的思路找寻递归关系式,怎么也寻找不到,但这道题好像是另一类问题的一个标准模板,就是求解卡塔兰数的具体组合是什么样的,这又是一种通用的解法。
对于这道题,第一个肯定是’(‘,接下来即可以是’(‘也可以是’)’,只需要满足下面三条规则:
left:表示剩余左括号的数目
right:表示剩余右括号的数目
满足的条件如下:
进行深度搜索就可以了,如下图: 
runtime:0ms
class Solution {
public:
    vector<string> generateParenthesis(int n) {
       vector<string> result;
       string path;
       helper(n,n,path,result);
       return result;
    }
    void helper(int left,int right,string path,vector<string> & result)
    {
        if(left==0&&right==0)
        {
            result.push_back(path);
            return ;
        }
        if(left!=0)
            helper(left-1,right,path+"(",result);
        if(right!=0&&left<right)
            helper(left,right-1,path+")",result);
    }
};版权声明:本文为博主原创文章,未经博主允许不得转载。
LeetCode22:Generate Parentheses
标签:
原文地址:http://blog.csdn.net/u012501459/article/details/46787097