Leetcode 22. 括号生成 dfs+回溯

给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

例如,给出 n = 3,生成结果为:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

此题要注意添加)的数目比(的数目小且还有剩余使才能添加。。。

当全部添加完毕时,return。

代码如下:
 

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> ve;
        if(n==0)
            return ve;
        dfs ("",n,n,ve);
        return ve;
    }
    void dfs (string s,int x,int y,vector<string>&ve)
    {
        if(x==0&&y==0)
        {
            ve.push_back(s);
            return;
        }
        if(x)
          dfs (s+'(',x-1,y,ve);
        if(y&&y>x)
          dfs (s+')',x,y-1,ve);
    }
};

猜你喜欢

转载自blog.csdn.net/qq_41410799/article/details/82494760