Print all combinations of balanced parentheses in C++


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 −
{}{}{}
{}{{}}
{{}}{}
{{}{}}
{{{}}}
raja
Published on 22-Jan-2020 12:35:09
Advertisements