Print all combinations of balanced parentheses

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

Examples:

Input : n=1
Output: {}

Input : n=2
Output: 
{}{}
{{}}

Algorithm:
Keep track of counts of open and close brackets.



  1. Initialize these counts as 0.
  2. Recursively call the _printParenthesis() function until open bracket count is less than the given n.
    • If open bracket count becomes more than the close bracket count, then put a closing bracket and recursively call for the remaining brackets.
    • If open bracket count is less than n, then put an opening bracket and call _printParenthesis() for the remaining brackets.

Thanks to Shekhu for providing the below code.

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:

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

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



My Personal Notes arrow_drop_up