LeetCode#22* Generate Parentheses

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Acmer_Sly/article/details/75268062

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:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]

题意:给一个整数n要求组合成一个由n对小括号组成的字符串,要求输出所有的可能排列情况。
思路:递归深搜,注意两个条件,能插入‘(’的条件是一定要剩余的数目大于0,能够插入‘)’的条件是一定要剩余的数目大于0 并且剩余的‘)’的数目大于剩余的‘(’的数目,不过一定要构造好Dfs函数的参数。

class Solution {
public:
    vector<string>ans;           
    vector<string> generateParenthesis(int n) {
        Dfs("",n,0);
        return ans;
    }
    void Dfs(string s,int l,int r)
    {
        if(l==0&&r==0)
        {
            ans.push_back(s);
            return;
        }
        if(l>0)
        {
            string s1=s+'(';
            Dfs(s1,l-1,r+1);
        }
        if(r>0)
        {
            string s1=s+')';
            Dfs(s1,l,r-1);
        }
    }
};

猜你喜欢

转载自blog.csdn.net/Acmer_Sly/article/details/75268062