Share a recursive C++ solution with only one integer counting left parenthesis--easy understand


  • 1
    B
        vector<string> generateParenthesis(int n) {
            vector<string> res;
            if(n){
                string s;
                generateParenthesis(res, s, n, 0);
            }
            return res;
        }
        
        void generateParenthesis(vector<string> &res, string s, int n, int left){
            if(!n){
                res.push_back(s);
                return ;
            }
            if(!left)
                generateParenthesis(res, s+'(', n, left+1);
            else{
                generateParenthesis(res, s+')', n-1, left-1);   // after a ')' is added, n would minus 1
                if(left<n)
                    generateParenthesis(res, s+'(', n, left+1);
            }
        }

Log in to reply
 

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