C++ backtracking solution.


  • 1
    C
    vector<string> generateParenthesis(int n) {
        vector<string> res;
        dfs(n, n, "", res);
        return res;
    }
    
    void dfs(int l, int r, string path, vector<string>& res) {
        if (l < 0 || r < 0 || l > r) 
            return;
        if (l == 0 && r == 0)
            res.push_back(path);
        dfs(l-1, r, path+'(', res);
        dfs(l, r-1, path+")", res);
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.