simple recursive c++ solution


  • 0
    M

    class Solution {
    public:

    //remaining is the number of parentheses that can still be opened
    //left_open is the number of parentheses that were previously opened and that need to be closed
    //the function recursively walks all possible paths that can be build with n pairs of parentheses.
    //remaining is the number of parentheses that can still be opened
    //left_open is the number of parentheses that still need to be closed
    void rec_generate(int remaining, int left_open, string s, vector<string>& v){
        
        if (remaining == 0 && left_open==0){
            v.push_back(s);
            return;
        }
        
        if (remaining>0){
            rec_generate(remaining-1, left_open+1, s+'(', v);
        }
        if (left_open>0){
            rec_generate(remaining, left_open-1, s+')',v);
        }
        return;
    }
    
    vector<string> generateParenthesis(int n) {
        
        string s;
        vector<string> v;
        
        rec_generate(n, 0, s, v);
        
        return v;
    }
    

    };


Log in to reply
 

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