Print all combinations of balanced parentheses

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++



filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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.

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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.
?>

chevron_right



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.

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up