Sunday, November 17, 2024
Google search engine
HomeData Modelling & AIPrint all combinations of balanced parentheses

Print all combinations of balanced parentheses

Given a number n, the task is to generate all possible n pairs of balanced parentheses.

Examples: 

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

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

Recommended Practice

Approach 1:

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:  

  • 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.
  • If the value of opening bracket and closing bracket is equal to n then print the string and return.
  • 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.
  • 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.

 Below is the implementation of above approach:

C++




#include <iostream>
 
#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) {
        std::cout << str << std::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);
        }
    }
}
 
// Driver program to test above functions
int main()
{
    int n = 3;
    printParenthesis(n);
    return 0;
}


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


Javascript




<script>
// javascript program to print all
// combinations of balanced parentheses
 
    // 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)
        {
         
            // print 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>


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


Output

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

Time complexity: O(2^n), as there are 2^n possible combinations of ‘(‘ and ‘)’ parentheses.
Auxiliary space: O(n), as n characters are stored in the str array.

Print all combinations of balanced parentheses using DFS

The idea is to use recursive Depth-First Search (DFS) approach that explores different combinations while ensuring the parentheses remain balanced. The program starts with an empty string and builds valid combinations by adding open and close parentheses, finally printing all the valid combinations found.

  • Create two variables left and right representing the number of remaining open parentheses and number of remaining close parentheses.
  • During each recursive call, two possibilities are explored:
    • Adding an open parenthesis ‘{‘ to the current combination and decrementing left.
    • Adding a close parenthesis ‘}‘ to the current combination and decrementing right.
  • If at any point, the number of open parentheses becomes greater than the number of close parentheses or either left or right becomes negative, the combination is invalid, and that branch of the recursion is terminated.
  • When both left and right are zero, it will indicate a valid combination has been formed.

 Below is the implementation of above approach:

C++




// c++ program to print all the combinations of balanced
// parenthesis.
#include <bits/stdc++.h>
using namespace std;
 
void generateParenthesis(int left, int right, string& s,
                         vector<string>& answer)
{
    // terminate
    if (left == 0 && right == 0) {
        answer.push_back(s);
    }
 
    if (left > right || left < 0 || right < 0) {
        // wrong
        return;
    }
 
    s.push_back('{');
    generateParenthesis(left - 1, right, s, answer);
    s.pop_back();
 
    s.push_back('}');
    generateParenthesis(left, right - 1, s, answer);
    s.pop_back();
}
 
int main()
{
    int n = 3;
    // vector ans is created to store all the possible valid
    // combinations of the parentheses.
    vector<string> ans;
    string s;
    // initially we are passing the counts of open and close
    // as 0, and the string s as an empty string.
    generateParenthesis(n, n, s, ans);
    // Now, here we print out all the combinations.
    for (auto k : ans) {
        cout << k << endl;
    }
    return 0;
}


Java




// Java program to print all the combinations of balanced
// parenthesis.
import java.util.*;
 
class GFG {
 
    // Function to generate all the combinations of
    // balanced parenthesis
    static void generateParenthesis(int left, int right,
                                    String s,
                                    List<String> answer)
    {
 
        // terminate
        if (left == 0 && right == 0) {
            answer.add(s);
        }
 
        if (left > right || left < 0 || right < 0) {
            // wrong
            return;
        }
 
        s += "{";
        generateParenthesis(left - 1, right, s, answer);
        s = s.substring(0, s.length() - 1);
 
        s += "}";
        generateParenthesis(left, right - 1, s, answer);
        s = s.substring(0, s.length() - 1);
    }
 
    public static void main(String[] args)
    {
        int n = 3;
 
        // vector ans is created to store all the possible
        // valid combinations of the parentheses.
        List<String> ans = new ArrayList<>();
        String s = "";
 
        // initially we are passing the counts of open and
        // close as 0, and the string s as an empty string.
        generateParenthesis(n, n, s, ans);
 
        // Now, here we print out all the combinations.
        for (String k : ans) {
            System.out.println(k);
        }
    }
}
 
// This code is contributed by Ajax


Python3




def generateParenthesis(left, right, s, answer):
    # terminate
    if left == 0 and right == 0:
        answer.append(s)
    if left > right or left < 0 or right < 0:
        # wrong
        return
    s += '{'
    generateParenthesis(left - 1, right, s, answer)
    s = s[:-1]
    s += '}'
    generateParenthesis(left, right - 1, s, answer)
    s = s[:-1]
 
 
n = 3
# list ans is created to store all the possible valid
# combinations of the parentheses.
ans = []
s = ""
# initially we are passing the counts of open and close
# as 0, and the string s as an empty string.
generateParenthesis(n, n, s, ans)
# Now, here we print out all the combinations.
for k in ans:
    print(k)


C#




using System;
using System.Collections.Generic;
 
namespace GFG {
public class Program {
    // Function to generate all the combinations of
    // balanced parenthesis
    static void generateParenthesis(int left, int right,
                                    string s,
                                    List<string> answer)
    {
        // terminate
        if (left == 0 && right == 0) {
            answer.Add(s);
        }
 
        if (left > right || left < 0 || right < 0) {
            // wrong
            return;
        }
 
        s += "{";
        generateParenthesis(left - 1, right, s, answer);
        s = s.Substring(0, s.Length - 1);
 
        s += "}";
        generateParenthesis(left, right - 1, s, answer);
        s = s.Substring(0, s.Length - 1);
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        int n = 3;
 
        // vector ans is created to store all the possible
        // valid combinations of the parentheses.
        List<string> ans = new List<string>();
        string s = "";
 
        // initially we are passing the counts of open and
        // close as 0, and the string s as an empty string.
        generateParenthesis(n, n, s, ans);
 
        // Now, here we print out all the combinations.
        foreach(string k in ans) { Console.WriteLine(k); }
    }
}
}
// This code contributed by SRJ


Javascript




<script>
  function generateParenthesis(left, right, s, answer) {
    // terminate
    if (left == 0 && right == 0) {
      answer.push(s);
    }
 
    if (left > right || left < 0 || right < 0) {
      // wrong
      return;
    }
 
    s += '{';
    generateParenthesis(left - 1, right, s, answer);
    s = s.slice(0, -1);
 
    s += '}';
    generateParenthesis(left, right - 1, s, answer);
    s = s.slice(0, -1);
  }
 
  function main() {
    let n = 3;
    // array ans is created to store all the possible valid
    // combinations of the parentheses.
    let ans = [];
    let s = '';
    // initially we are passing the counts of open and close
    // as 0, and the string s as an empty string.
    generateParenthesis(n, n, s, ans);
    // Now, here we print out all the combinations.
    for (let k of ans) {
      console.log(k);
    }
  }
 
  main();
</script>


Output

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

Time Complexity: O(2^n)
Auxiliary Space:  O(n)

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

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments