22. 括号生成(LeetCode中等)(DFS)

22. 括号生成

class Solution {
public:
    vector<string> ans;

    vector<string> generateParenthesis(int n) {
        dfs(n, 0, 0, "");

        return ans;    
    }

    void dfs(int n, int lc, int rc, string path){
        if(lc == n && rc == n){
            ans.push_back(path); return;
        }
        if(lc < n) dfs(n, lc + 1, rc , path + '(');
        if(rc < n && rc < lc) dfs(n, lc, rc + 1, path + ')');
    }
};
posted @ 2025-03-15 16:12  awei040519  阅读(17)  评论(0)    收藏  举报