Easy C++ solution with comments


#1

void findallparanthesis(vector &result,string &current,int required,int l1,int l2){
// l1 for storing the number of “(”
// l2 for storing the number of “)”
if(l1>required || l2>required){
return;
}

if(l2>l1){
return;
}

if(l1==required && l2==required){
result.push_back(current); // condition when we get the solution
return;
}

current.push_back(’(’);
findallparanthesis(result,current,required,l1+1,l2);
current.pop_back(); // Backtrack

current.push_back(’)’);
findallparanthesis(result,current,required,l1,l2+1);
current.pop_back(); // Backtrack

return;
}

vector Solution::generateParenthesis(int A) {
vector result;
string current="";

findallparanthesis(result,current,A,0,0);

return result;
// Happy Coding 

}


#2

can you please explain,why you have taken (l2>l1)


#3

consider this case “( ( ( ) ) ) )”
here the number of “(” is 3 while the number of “)” is 4 and this can never be a solution as you cannot close a paranthesis before opening of the same paranthesis.
Hope you understand the solution.


#4

This was really good man, thanks


#5

Less checks are required in my code

     void help(int mx, int open, int close, string curr, vector<string>& res){
            if(open == mx && close == mx){
                res.push_back(curr);
                return;
            }
            if(open < mx){
                curr += '(';
                help(mx, open + 1, close, curr, res);
                curr.pop_back();
            }
            if(close < open){
                curr += ')';
                help(mx, open, close + 1, curr, res);
                curr.pop_back();
            }
            return;
        }
        vector<string> Solution::generateParenthesis(int A) {
            vector<string> res;
            help(A, 0, 0, "", res);
            return res;
        }