Print all combinations of balanced parentheses
Write a function 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.
Implementation:
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 |
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 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> |
{{}} {}{}
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.
Let’s see the implementation of the same algorithm in a slightly different, simple and concise way :
C++
// c++ program to print all the combinations of balanced // parenthesis. #include <bits/stdc++.h> using namespace std; // function which generates all possible n pairs of balanced // parentheses. open : count of the number of open // parentheses used in generating the current string s. close // : count of the number of closed parentheses used in // generating the current string s. s : currently generated // string/ ans : a vector of strings to store all the valid // parentheses. void generateParenthesis( int n, int open, int close, string s, vector<string>& ans) { // if the count of both open and close parentheses // reaches n, it means we have generated a valid // parentheses. So, we add the currently generated string // s to the final ans and return. if (open == n && close == n) { ans.push_back(s); return ; } // At any index i in the generation of the string s, we // can put an open parentheses only if its count until // that time is less than n. if (open < n) { generateParenthesis(n, open + 1, close, s + "{" , ans); } // At any index i in the generation of the string s, we // can put a closed parentheses only if its count until // that time is less than the count of open parentheses. if (close < open) { generateParenthesis(n, open, close + 1, s + "}" , ans); } } int main() { int n = 3; // vector ans is created to store all the possible valid // combinations of the parentheses. vector<string> ans; // initially we are passing the counts of open and close // as 0, and the string s as an empty string. generateParenthesis(n, 0, 0, "" , ans); // Now, here we print out all the combinations. for ( auto s : ans) { cout << s << endl; } return 0; } |
Java
// Java program to print all the combinations of balanced // parenthesis. import java.util.*; class GFG { // function which generates all possible n pairs of // balanced parentheses. // open : count of the number of open parentheses used // in generating the current string s. close : count of // the number of closed parentheses used in generating // the current string s. s : currently generated string/ // ans : a vector of strings to store all the valid // parentheses. public static void generateParenthesis( int n, int open, int close, String s, ArrayList<String> ans) { // if the count of both open and close parentheses // reaches n, it means we have generated a valid // parentheses. So, we add the currently generated // string s to the final ans and return. if (open == n && close == n) { ans.add(s); return ; } // At any index i in the generation of the string s, // we can put an open parentheses only if its count // until that time is less than n. if (open < n) { generateParenthesis(n, open + 1 , close, s + "{" , ans); } // At any index i in the generation of the string s, // we can put a closed parentheses only if its count // until that time is less than the count of open // parentheses. if (close < open) { generateParenthesis(n, open, close + 1 , s + "}" , ans); } } public static void main(String[] args) { int n = 3 ; // vector ans is created to store all the possible // valid combinations of the parentheses. ArrayList<String> ans = new ArrayList<>(); // initially we are passing the counts of open and // close as 0, and the string s as an empty string. generateParenthesis(n, 0 , 0 , "" , ans); // Now, here we print out all the combinations. for (String s : ans) { System.out.println(s); } } } // This code is contributed by ninja_hattori |
Python3
# Python program to print all the combinations of balanced parenthesis. # function which generates all possible n pairs of balanced parentheses. # open : count of the number of open parentheses used in generating the current string s. # close : count of the number of closed parentheses used in generating the current string s. # s : currently generated string/ # ans : a vector of strings to store all the valid parentheses. def generateParenthesis(n, Open , close, s, ans): # if the count of both open and close parentheses reaches n, it means we have generated a valid parentheses. # So, we add the currently generated string s to the final ans and return. if ( Open = = n and close = = n): ans.append(s) return # At any index i in the generation of the string s, we can put an open parentheses only if its count until that time is less than n. if ( Open < n): generateParenthesis(n, Open + 1 , close, s + "{" , ans) # At any index i in the generation of the string s, we can put a closed parentheses only if its count until that time is less than the count of open parentheses. if (close < Open ): generateParenthesis(n, Open , close + 1 , s + "}" , ans) n = 3 # ans is created to store all the possible valid combinations of the parentheses. ans = [] # initially we are passing the counts of open and close as 0, and the string s as an empty string. generateParenthesis(n, 0 , 0 , "", ans) # Now, here we print out all the combinations. for s in ans: print (s) # This code is contributed by ninja_hattori. |
C#
// C# program to print all the combinations of balanced // parenthesis. using System; using System.Collections; public class GFG { // function which generates all possible n pairs of // balanced parentheses. // open : count of the number of open parentheses used // in generating the current string s. close : count of // the number of closed parentheses used in generating // the current string s. s : currently generated string/ // ans : a vector of strings to store all the valid // parentheses. static public void generateParenthesis( int n, int open, int close, string s, ArrayList ans) { // if the count of both open and close parentheses // reaches n, it means we have generated a valid // parentheses. So, we add the currently generated // string s to the final ans and return. if (open == n && close == n) { ans.Add(s); return ; } // At any index i in the generation of the string s, // we can put an open parentheses only if its count // until that time is less than n. if (open < n) { generateParenthesis(n, open + 1, close, s + "{" , ans); } // At any index i in the generation of the string s, // we can put a closed parentheses only if its count // until that time is less than the count of open // parentheses. if (close < open) { generateParenthesis(n, open, close + 1, s + "}" , ans); } } static public void Main() { // Code int n = 3; // vector ans is created to store all the possible // valid combinations of the parentheses. ArrayList ans = new ArrayList(); // initially we are passing the counts of open and // close as 0, and the string s as an empty string. generateParenthesis(n, 0, 0, "" , ans); // Now, here we print out all the combinations. for ( int i = 0; i < ans.Count; i++) { Console.WriteLine(ans[i]); } } } // This code is contributed by ninja_hattori. |
Javascript
<script> // JavaScript program to print all the combinations of balanced parenthesis. // function which generates all possible n pairs of balanced parentheses. // open : count of the number of open parentheses used in generating the current string s. // close : count of the number of closed parentheses used in generating the current string s. // s : currently generated string/ // ans : an array of strings to store all the valid parentheses. function generateParenthesis(n, open, close, s, ans) { // if the count of both open and close parentheses reaches n, it means we have generated a valid parentheses. // So, we add the currently generated string s to the final ans and return. if (open == n && close == n){ ans.push(s); return ; } // At any index i in the generation of the string s, we can put an open parentheses only if its count until that time is less than n. if (open < n) { generateParenthesis(n, open + 1, close, s + "{" , ans); } // At any index i in the generation of the string s, we can put a closed parentheses only if its count until that time is less than the count of open parentheses. if (close < open) { generateParenthesis(n, open, close + 1, s + "}" , ans); } } // Driver code let n = 3; // array of strings ans is created to store all the possible valid combinations // of the parentheses. let ans = []; // initially we are passing the counts of open and close as 0, // and the string s as an empty string. generateParenthesis(n, 0, 0, "" , ans); // Now, here we print out all the combinations. for (let i = 0; i < ans.length; i++) { document.write(ans[i]); } // This code is contributed by shinjanpatra </script> |
{{{}}} {{}{}} {{}}{} {}{{}} {}{}{}
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 upper bound of time complexity is O(2^n) or it has exponential time complexity. - Auxiliary Space: O(n).
The space complexity can be reduced to O(n) if global variable or static variable is used to store the output string.
Approach 2: Using DFS
Algorithm:
- First, the n represents the times we can use parentheses, ex: n = 3 means we have {{{}}} can use.
- In each recursion, we try put { and } once, when left “{” > right “}” , means it will start from } . It’s definitely wrong, so we get rid of the following recursions. { It’s kind of pruning.
- Another situation is either left and right is less than 0, we will break the recursion.
- Only when left and right both equal to 0, the string s will be push into answer vector. Because they both are 0 means we use all the parentheses.
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 |
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> |
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) |
{{{}}} {{}{}} {{}}{} {}{{}} {}{}{}
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.
Please Login to comment...