Generate Parentheses | Practice | GeeksforGeeks

Given an integer N representing the number of pairs of parentheses, the task is to generate all combinations of well-formed(balanced) parentheses.

Example 1:
Input:
N = 3
Output:
((()))
(()())
(())()
()(())
()()()

Input:
N = 1
Output:
()

0
sarthakpandey200218 hours ago
SIMPLE C++ SOLUTION 
void solve(string out,vector<string>&ans,int open,int close){       //int open=n;       //int close=n;       if(open==0 && close==0){           ans.push_back(out);           return;       }       if(open!=0){           string op1=out;           op1.push_back('(');           solve(op1,ans,open-1,close);       }       if(close>open){           string op2=out;           op2.push_back(')');           solve(op2,ans,open,close-1);       }       return;   }   vector<string> AllParenthesis(int n)    {       // Your code goes here        vector<string>ans;       int open=n;       int close=n;       solve("",ans,open,close);       return ans;   }}; 
0
rounakdiptaghosh19992 weeks ago
void solve(int open , int close,vector<string>&ans,string op)
    {
        if(open==0 and close==0){
            ans.push_back(op);
            return ;
        }
        
        if(open!=0){
           string op1 = op ;
           op1.push_back('(');
           solve(open-1,close,ans,op1);
        }
        if(close>open){
         string op2=op;
         op2.push_back(')');
         solve(open,close-1,ans,op2);
        }
        return ;
    }
    
    vector<string> AllParenthesis(int n) 
    {
        // Your code goes here 
        vector<string> ans;
        int open=n;
        int close=n;
        string op="";
        solve(open , close , ans ,op);
        return ans;
        
+1
shourya17agarwal3 weeks ago
There us an error with python compiler. IT shows wrong output while submitting. but correct while testing.
0
bokonist3 weeks ago
Simple C++ recursive solution with comments.
TC: O(2^N * N)
.
.
.
void paran(int n, int open, int close, string s, vector<string> &ans)
{
    //try to picture the recursion tree, at every point, there are two choices, add an opening or a closing
    // when opening and closing reaches n, we have one of our ans strings
    if(open==n && close==n)
    {
        ans.push_back(s);
        return;
    } 
    if(open<n)
        paran(n, open+1, close, s+"(", ans);
    if(close<open)
        paran(n, open, close+1, s+")", ans);
}
vector<string> AllParenthesis(int n) 
{
    // Your code goes here 
    vector<string> ans;
    paran(n, 0,0,"",ans);
    return ans;
        
}
0
aanandhub4 weeks ago
List<String> str = new ArrayList<String>();      public List<String> AllParenthesis(int n)    {       // Write your code here       return Paranthesis("",0,0,n);   }      public List<String> Paranthesis(String temp, int start, int close, int n)   {
       if(close > start)       {           return str;       }       if(start + close == n*2)       {           if(start == close)           {               str.add(String.valueOf(temp));               return str;            }           else           {               return str;           }                  }              Paranthesis(temp+"(", start+1, close, n);       Paranthesis(temp+")", start, close+1, n);       return str;   }
+1
adarshgupta4014 weeks ago
Easy Java Recursive Soln→
class Solution {
    
    public List<String> AllParenthesis(int n) 
    {
        List<String> list = new ArrayList<>();

        int open= n, close= n;
        String op= "";
        helper(open, close,  op, list);
        return list;
    }
    public void helper(int open, int close, String op, List<String> list) {
        //base
        if(open == 0 && close == 0) {
            list.add(op);
            return;
        }
        if(open > 0 ){
            String op1 = op;
            op1 += '(';
            helper(open-1, close, op1, list);
        }
        if(close > open){
            String op2 = op;
            op2 += ')';
            helper(open, close-1, op2, list);
        }
        return;
    }
}

+1
scien-terrific1 month ago
C++ BackTracking Solution
class Solution
{
    vector<string>res;
    private:
    void helper(string &s,int open,int close){
        if(!open and !close){
            res.push_back(s);
            return;
        }
        if(open){
            s+="(";
            helper(s,open-1,close);
            s.pop_back();
        }
        if(close and close>open){
            s+=")";
            helper(s,open,close-1);
            s.pop_back();
        }
    }
    public:
    vector<string> AllParenthesis(int n) 
    {
        if(!n)return {};
        string s="";
        helper(s,n,n);
        return res;
    }
};
+1
abytespaceneeded1 month ago
// upvote if you like the solution.

class Solution
{
    public:
    vector<string> ans;
    
    void solve(string temp, int open, int close)
    {
        if(open == 0 && close == 0)
        {
            ans.push_back(temp);
            return ;
        }
        
        if(open == close)
            solve(temp+'(',open-1,close);
        else if(open == 0 && close != 0)
            solve(temp+')',open,close-1);
        else
        {
            solve(temp+'(',open-1,close);
            solve(temp+')',open,close-1);
        }
    }
    
    vector<string> AllParenthesis(int n) 
    {
        solve("",n,n);
        
        return ans;
    }
};
0
aloksinghbais021 month ago
C++ solution having time complexity as O((2^N)*N) and space complexity as O((2^N)*X) is as follows :- 
 
Execution Time :- 0.9 / 1.5 sec
 
vector<string> ans;      bool isValid(string str,int cnt1,int cnt2){       if(cnt1 != cnt2) return (false);       stack<char> stk;       for(auto &ch: str){           if(ch == '(') stk.push(ch);           else{               if(stk.empty()) return (false);               if(stk.top() != '(') return (false);               stk.pop();           }       }       if(!stk.empty()) return (false);       return (true);   }      void helper(int i,string output,int cnt1,int cnt2,int n){       if(i == 2*n){           if(isValid(output,cnt1,cnt2)){               ans.push_back(output);           }           return;       }              if(cnt1 <= n) helper(i+1,output+'(',cnt1+1,cnt2,n);       if(cnt2 <= n && cnt1 > cnt2) helper(i+1,output+')',cnt1,cnt2+1,n);   }      vector<string> AllParenthesis(int n) {       string output{};       helper(0,output,0,0,n);       return (ans);   }
0
kashyapjhon2 months ago
C++ Solution Input Output Approach
Time=(0.3/1.5) MEDIUM:
void help(vector<string> &u,int l,int r,string out){       if(l==0 && r==0){           u.push_back(out);           return;       }       if(l!=0){           string out1=out;           out1.push_back('(');           help(u,l-1,r,out1);       }       if(l<r){           string out2=out;           out2.push_back(')');           help(u,l,r-1,out2);       }       return;   }   vector<string> AllParenthesis(int n)    {       // Your code goes here       vector<string> u;       int l=n;       int r=n;       string out="";       help(u,l,r,out);       return u;   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.