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.
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);
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);
}
}
}
int main()
{
int n = 3;
printParenthesis(n);
return 0;
}
|
C
#include <stdio.h>
#define MAX_SIZE 100
void _printParenthesis( int pos, int n, int open, int close);
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);
}
}
}
int main()
{
int n = 3;
printParenthesis(n);
getchar ();
return 0;
}
|
Java
import java.io.*;
class GFG {
static void _printParenthesis( char str[], int pos,
int n, int open,
int close)
{
if (close == n) {
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);
}
}
}
static void printParenthesis( char str[], int n)
{
if (n > 0 )
_printParenthesis(str, 0 , n, 0 , 0 );
return ;
}
public static void main(String[] args)
{
int n = 3 ;
char [] str = new char [ 2 * n];
printParenthesis(str, n);
}
}
|
Python3
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)
n = 3
str = [""] * 2 * n
printParenthesis( str , n)
|
C#
using System;
class GFG {
static void _printParenthesis( char [] str, int pos,
int n, int open,
int close)
{
if (close == n) {
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);
}
}
}
static void printParenthesis( char [] str, int n)
{
if (n > 0)
_printParenthesis(str, 0, n, 0, 0);
return ;
}
public static void Main()
{
int n = 3;
char [] str = new char [2 * n];
printParenthesis(str, n);
}
}
|
Javascript
<script>
function _printParenthesis( str , pos , n , open , close)
{
if (close == n)
{
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);
}
}
}
function printParenthesis( str , n)
{
if (n > 0)
_printParenthesis(str, 0, n, 0, 0);
return ;
}
var n = 3;
var str = new Array(2 * n);
printParenthesis(str, n);
</script>
|
PHP
<?php
$MAX_SIZE = 100;
function printParenthesis( $str , $n )
{
if ( $n > 0)
_printParenthesis( $str , 0,
$n , 0, 0);
return ;
}
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 );
}
}
}
$n = 3;
$str = " " ;
printParenthesis( $str , $n );
?>
|
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++
#include <bits/stdc++.h>
using namespace std;
void generateParenthesis( int left, int right, string& s,
vector<string>& answer)
{
if (left == 0 && right == 0) {
answer.push_back(s);
}
if (left > right || left < 0 || right < 0) {
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<string> ans;
string s;
generateParenthesis(n, n, s, ans);
for ( auto k : ans) {
cout << k << endl;
}
return 0;
}
|
Java
import java.util.*;
class GFG {
static void generateParenthesis( int left, int right,
String s,
List<String> answer)
{
if (left == 0 && right == 0 ) {
answer.add(s);
}
if (left > right || left < 0 || right < 0 ) {
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 ;
List<String> ans = new ArrayList<>();
String s = "" ;
generateParenthesis(n, n, s, ans);
for (String k : ans) {
System.out.println(k);
}
}
}
|
Python3
def generateParenthesis(left, right, s, answer):
if left = = 0 and right = = 0 :
answer.append(s)
if left > right or left < 0 or right < 0 :
return
s + = '{'
generateParenthesis(left - 1 , right, s, answer)
s = s[: - 1 ]
s + = '}'
generateParenthesis(left, right - 1 , s, answer)
s = s[: - 1 ]
n = 3
ans = []
s = ""
generateParenthesis(n, n, s, ans)
for k in ans:
print (k)
|
C#
using System;
using System.Collections.Generic;
namespace GFG {
public class Program {
static void generateParenthesis( int left, int right,
string s,
List< string > answer)
{
if (left == 0 && right == 0) {
answer.Add(s);
}
if (left > right || left < 0 || right < 0) {
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;
List< string > ans = new List< string >();
string s = "" ;
generateParenthesis(n, n, s, ans);
foreach ( string k in ans) { Console.WriteLine(k); }
}
}
}
|
Javascript
<script>
function generateParenthesis(left, right, s, answer) {
if (left == 0 && right == 0) {
answer.push(s);
}
if (left > right || left < 0 || right < 0) {
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;
let ans = [];
let s = '' ;
generateParenthesis(n, n, s, ans);
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 geeks!