LeetCode 22. 括号生成

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

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

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

算法:暴搜(dfs)。我们搜索出所有的结果并进行保存即可。

class Solution {
public:
    vector<string>res;
    void dfs(int l,int r,int n,string cur){
        if(l==n&&r==n){
            res.push_back(cur);
            return ;
        }
        if(l<n)
            dfs(l+1,r,n,cur+"(");
        if(r<l)
            dfs(l,r+1,n,cur+")");
    }
    vector<string> generateParenthesis(int n) {
        if(n==0)
            return {""};
        dfs(0,0,n,"");
        return res;
    }
};

 

posted @ 2019-07-11 18:57  YF-1994  阅读(98)  评论(0编辑  收藏  举报