zl程序教程

您现在的位置是:首页 >  其他

当前栏目

【LeetCode 22】括号生成

LeetCode 生成 22 括号
2023-09-14 09:03:43 时间

题目链接

【题解】

一道傻逼回溯法。 每次都有两个选择,加个左括号。 加个右括号。无非加个判断啥时候不能加右括号了。

【代码】

class Solution {
public:
    vector<string> ans;
    void dfs(int rest,int cur,string state){
        if (cur>rest) return;
        if (rest==0 && cur==0){
            ans.push_back(state);
        }
        if (cur>0){
            dfs(rest-1,cur-1,state+")");
        }
        dfs(rest,cur+1,state+"(");
    }
    vector<string> generateParenthesis(int n) {
        ans.clear();
        dfs(n,0,"");
        return ans;
    }
};