An easy C++ solution using recursion


  • 6
    U
    class Solution {
    public:
        #include<vector>
        vector <string> ans;
        
        void para(int i,int open,int n,string s)
        {
            if(open < 0)    return;
            if(i==n)
            {
                if(open==0)
                    ans.push_back(s);
                return;
            }
            para(i+1,open+1,n,s+"(");   
            para(i+1,open-1,n,s+")");
        }
    
        vector<string> generateParenthesis(int n) {
            
            string s = "";
            para(0,0,2*n,s);
            return ans;
        }
    };

  • 0
    R

    analyse space and time complexity please


  • 0
    J

    I think your algorithm was inspired from this original solution


Log in to reply
 

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