Skip to content
Related Articles

Related Articles

Improve Article

Print all combinations of balanced parentheses

  • Difficulty Level : Hard
  • Last Updated : 28 Jun, 2021

Write a function to generate all possible n pairs of balanced parentheses. 

Examples: 

Input: n=1
Output: {}
Explantaion: This the only sequence of balanced 
parenthesis formed using 1 pair of balanced parenthesis. 

Input : n=2
Output: 
{}{}
{{}}
Explantaion: This the only two sequences of balanced 
parenthesis formed using 2 pair of balanced parenthesis. 
 

Approach: To form all the sequences of balanced bracket subsequences with n pairs. So there are n opening brackets and n closing brackets. 
So the subsequence will be of length 2*n. There is a simple idea, the i’th character can be ‘{‘ if and only if the count of ‘{‘ till i’th is less than n and i’th character can be ‘}’ if and only if the count of ‘{‘ is greater than the count of ‘}’ till index i. If these two cases are followed then the resulting subsequence will always be balanced. 
So form the recursive function using the above two cases.

Algorithm:  

  1. Create a recursive function that accepts a string (s), count of opening brackets (o) and count of closing brackets (c) and the value of n.
  2. if the value of opening bracket and closing bracket is equal to n then print the string and return.
  3. If the count of opening bracket is greater than count of closing bracket then call the function recursively with the following parameters String s + “}”, count of opening bracket o, count of closing bracket c + 1, and n.
  4. If the count of opening bracket is less than n then call the function recursively with the following parameters String s + “{“, count of opening bracket o + 1, count of closing bracket c, and n.



Implementation: 

C++




// C++ program to print all 
// combinations of balanced parentheses
#include <iostream>
#define MAX_SIZE 100
  
using namespace std;
  
void _printParenthesis(int pos, int n, 
                       int open, int close)
{
    static char str[MAX_SIZE];    
       
    if (close == n)
    {
        cout << str << endl;
        return;
    }
    else
    {
        if (open > close)
        {
            str[pos] = '}';
            _printParenthesis(pos + 1, n, open,
                            close + 1);
        }
           
        if (open < n)
        {
            str[pos] = '{';
            _printParenthesis(pos + 1, n, 
                             open + 1, close);
        }
    }
}
  
// Wrapper over _printParenthesis()
void printParenthesis(int n)
{
    if (n > 0)
        _printParenthesis(0, n, 0, 0);
          
    return;
}    
   
// Driver code
int main()
{
    int n = 3;
      
    printParenthesis(n);
  
    return 0;
}
  
// This code is contributed by hemanth lishetti

C




// C program to Print all combinations 
// of balanced parentheses 
# include<stdio.h> 
# define MAX_SIZE 100 
  
void _printParenthesis(int pos, int n, int open, int close); 
  
// Wrapper over _printParenthesis() 
void printParenthesis(int n) 
    if(n > 0) 
        _printParenthesis(0, n, 0, 0); 
    return
}     
  
void _printParenthesis(int pos, int n, int open, int close) 
    static char str[MAX_SIZE];     
      
    if(close == n) 
    
        printf("%s \n", str); 
        return
    
    else
    
        if(open > close) 
        
            str[pos] = '}'
            _printParenthesis(pos+1, n, open, close+1); 
        
          
        if(open < n) 
        
        str[pos] = '{'
        _printParenthesis(pos+1, n, open+1, close); 
        
    
  
// Driver program to test above functions 
int main() 
    int n = 3; 
    printParenthesis(n); 
    getchar(); 
    return 0; 
}

Java




// Java program to print all 
// combinations of balanced parentheses
import java.io.*;
  
class GFG 
{
    // Function that print all combinations of 
    // balanced parentheses
    // open store the count of opening parenthesis
    // close store the count of closing parenthesis
    static void _printParenthesis(char str[], int pos, int n, int open, int close)
    {
        if(close == n) 
        {
            // print the possible combinations
            for(int i=0;i<str.length;i++)
                System.out.print(str[i]);
            System.out.println();
            return;
        }
        else
        {
            if(open > close) {
                str[pos] = '}';
                _printParenthesis(str, pos+1, n, open, close+1);
            }
            if(open < n) {
                str[pos] = '{';
                _printParenthesis(str, pos+1, n, open+1, close);
            }
        }
    }
      
    // Wrapper over _printParenthesis()
    static void printParenthesis(char str[], int n)
    {
        if(n > 0)
        _printParenthesis(str, 0, n, 0, 0);
        return;
    }
      
    // driver program 
    public static void main (String[] args) 
    {
        int n = 3;
        char[] str = new char[2 * n];
        printParenthesis(str, n);
    }
}
  
// Contributed by Pramod Kumar

Python3




# Python3 program to
# Print all combinations
# of balanced parentheses
  
# Wrapper over _printParenthesis()
def printParenthesis(str, n):
    if(n > 0):
        _printParenthesis(str, 0
                          n, 0, 0);
    return;
  
def _printParenthesis(str, pos, n, 
                      open, close):
      
    if(close == n):
        for i in str:
            print(i, end = "");
        print();
        return;
    else:
        if(open > close):
            str[pos] = '}';
            _printParenthesis(str, pos + 1, n, 
                              open, close + 1);
        if(open < n):
            str[pos] = '{';
            _printParenthesis(str, pos + 1, n, 
                              open + 1, close);
  
# Driver Code
n = 3;
str = [""] * 2 * n;
printParenthesis(str, n);
  
# This Code is contributed
# by mits.

C#




// C# program to print all 
// combinations of balanced parentheses
using System;
  
class GFG
{
    // Function that print all combinations of 
    // balanced parentheses
    // open store the count of opening parenthesis
    // close store the count of closing parenthesis
    static void _printParenthesis(char []str,
            int pos, int n, int open, int close)
    {
        if (close == n) 
        {
            // print the possible combinations
            for (int i = 0; i < str.Length; i++)
                Console.Write(str[i]);
              
            Console.WriteLine();
            return;
        }
        else
        {
            if (open > close) {
                str[pos] = '}';
                _printParenthesis(str, pos + 1,
                                n, open, close + 1);
            }
            if (open < n) {
                str[pos] = '{';
                _printParenthesis(str, pos + 1,
                                n, open + 1, close);
            }
        }
    }
      
    // Wrapper over _printParenthesis()
    static void printParenthesis(char []str, int n)
    {
        if(n > 0)
        _printParenthesis(str, 0, n, 0, 0);
        return;
    }
      
    // driver program 
    public static void Main() 
    {
        int n = 3;
        char[] str = new char[2 * n];
          
        printParenthesis(str, n);
    }
}
  
// This code is contributed by Sam007

PHP




<?php
// PHP program to Print 
// all combinations of 
// balanced parentheses
$MAX_SIZE = 100;
  
// Wrapper over 
// _printParenthesis()
function printParenthesis($str, $n)
{
    if($n > 0)
        _printParenthesis($str, 0, 
                          $n, 0, 0);
    return;
  
// Function that print 
// all combinations of 
    // balanced parentheses
    // open store the count of
    //  opening parenthesis
    // close store the count of 
    //  closing parenthesis
function _printParenthesis($str, $pos, $n
                           $open, $close)
{
    if($close == $n
    {
        for ($i = 0; 
             $i < strlen($str); $i++)
        echo $str[$i];
        echo "\n";
        return;
    }
    else
    {
        if($open > $close
        {
            $str[$pos] = '}';
            _printParenthesis($str, $pos + 1, $n,
                              $open, $close + 1);
        }
          
        if($open < $n)
        {
        $str[$pos] = '{';
        _printParenthesis($str, $pos + 1, $n
                          $open + 1, $close);
        }
    }
}
  
// Driver Code
$n = 3;
$str="     ";
printParenthesis($str, $n);
  
// This Code is contributed by mits.
?>

Javascript




<script>
// javascript program to prvar all 
// combinations of balanced parentheses
  
    // Function that prvar all combinations of
    // balanced parentheses
    // open store the count of opening parenthesis
    // close store the count of closing parenthesis
    function _printParenthesis( str , pos , n , open , close) 
    {
        if (close == n)
        {
          
            // prvar the possible combinations
            for (let i = 0; i < str.length; i++)
                document.write(str[i]);
            document.write("<br/>");
            return;
        
        else
        {
            if (open > close)
            {
                str[pos] = '}';
                _printParenthesis(str, pos + 1, n, open, close + 1);
            }
            if (open < n) 
            {
                str[pos] = '{';
                _printParenthesis(str, pos + 1, n, open + 1, close);
            }
        }
    }
  
    // Wrapper over _printParenthesis()
    function printParenthesis( str , n)
    {
        if (n > 0)
            _printParenthesis(str, 0, n, 0, 0);
        return;
    }
  
    // Driver program
    var n = 3;
    var str = new Array(2 * n);
    printParenthesis(str, n);
  
// This code is contributed by shikhasingrajput 
</script>

Output: 

{}{}{}
{}{{}}
{{}}{}
{{}{}}
{{{}}}

Thanks to Shekhu for providing the above code.
Complexity Analysis: 

  • Time Complexity: O(2^n). 
    For every index there can be two options ‘{‘ or ‘}’. So it can be said that the upperbound of time complexity is O(2^n) or it has exponential time complexity.
  • Space Complexity: O(n). 
    The space complexity can be reduced to O(n) if global variable or static variable is used to store the output string.

Please write comments if you find the above codes/algorithms incorrect, or find better ways to solve the same problem.
 

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :