# Print all combinations of balanced parentheses in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

In this problem, we are given an integer n. Our task is to print all possible pairs of n balanced parentheses.

Balanced parentheses are parentheses pairs that have a closing symbol for every corresponding opening symbol. Also, pairs should be properly nested.

Let’s take an example to understand the problem,

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

To solve this problem, we need to keep track of pairs of brackets. The initial count of brackets is 0. Then we will recursively a function till the total bracket count is less than n. Count brackets, recursively call for brackets based on the count. If opening bracket count is more than closing, put closing brackets and then go for a remaining count of pairs, if the opening bracket is less than n recursively call for remaining bracket pairs.

## Example

The below code with show implementation of our solution,

Live Demo

# include<iostream>
using namespace std;
# define MAX_COUNT 100
void printParenthesesPairs(int pos, int n, int open, int close){
static char str[MAX_COUNT];
if(close == n) {
cout<<str<<endl;
return;
}
else {
if(open > close) {
str[pos] = '}';
printParenthesesPairs(pos+1, n, open, close+1);
}
if(open < n) {
str[pos] = '{';
printParenthesesPairs(pos+1, n, open+1, close);
}
}
}
int main() {
int n = 3;
cout<<"All parentheses pairs of length "<<n<<" are:\n";
if(n > 0)
printParenthesesPairs(0, n, 0, 0);
getchar();
return 0;
}

## Output

All parentheses pairs of length 3 are −
{}{}{}
{}{{}}
{{}}{}
{{}{}}
{{{}}}
Updated on 22-Jan-2020 12:36:07

Advertisements