leetcode22 括号生成

题目https://leetcode-cn.com/problems/generate-parentheses/

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

样例输入与输出

n = 3
输出:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

思路

  • 不难想出直接暴力的做法,每个位置上有"("和")"两种选择,总共有2^n种情况。但可以进行优化,因为第一个括号一定是"(",并且只有在有"("时才能放置")",因此记录左括号的个数,每放一个右括号,左括号的数目减1,当左括号数目为0时,下一位置不能放置右括号。

代码

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> ans;
        string str; str.resize(2*n);
        dfs(0, n, str, ans, 0);
        return ans;
    }
private:
    void dfs(int idx, int n, string& str, vector<string>& ans, int l){
        if(idx == 2*n){
            if(l == 0){
                ans.push_back(str);
            }
            return;
        }
        str[idx] = '('; dfs(idx+1, n, str, ans, l+1);
        if(l)
            {str[idx] = ')'; dfs(idx+1, n, str, ans, l-1); }
    }
};
posted @ 2020-01-30 17:23  patrolli  阅读(158)  评论(0编辑  收藏  举报