LeetCode22: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:

“((()))”, “(()())”, “(())()”, “()(())”, “()()()”

如果这道题是求上面括号的组合有多少种方式,那么这是一道卡塔兰数的题目,最开始就陷入到这里了,按照卡塔兰数的思路找寻递归关系式,怎么也寻找不到,但这道题好像是另一类问题的一个标准模板,就是求解卡塔兰数的具体组合是什么样的,这又是一种通用的解法。

对于这道题,第一个肯定是’(‘,接下来即可以是’(‘也可以是’)’,只需要满足下面三条规则:

left:表示剩余左括号的数目
right:表示剩余右括号的数目

满足的条件如下:

  1. 当left=0&&right=0时表示找到一条路径
  2. 当left!=0时可以向左子树伸展
  3. 当right!=0&&left< right时可以向右子树伸展

进行深度搜索就可以了,如下图:
LeetCode22:Generate Parentheses_第1张图片

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)