C++ program to find n valid bracket sequences


Suppose we have a number n. As we know, a bracket sequence is a string containing only characters "(" and ")". A valid bracket sequence is a bracket sequence which can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. So, if a bracket sequence is like "()()" this is valid because we can put 1's like "(1)+(1)". From number n, we have to find exactly n different possible valid bracket sequences of length 2n.

So, if the input is like n = 4, then the output will be ["()()()()", "(())()()", "((()))()", "(((())))"]

Steps

To solve this, we will follow these steps −

for initialize k := 1, when k <= n, update (increase k by 1), do:
   for initialize i := 1, when i <= k, update (increase i by 1), do:
      print "("
   for initialize i := 1, when i <= k, update (increase i by 1), do:
      print ")"
   for initialize i := k + 1, when i <= n, update (increase i by 1), do:
      print "()"
   go to next line

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

void solve(int n) {
   for (int k = 1; k <= n; k++) {
      for (int i = 1; i <= k; i++)
         cout << "(";
      for (int i = 1; i <= k; i++)
         cout << ")";
      for (int i = k + 1; i <= n; i++)
         cout << "()";
      cout << endl;
   }
}
int main() {
   int n = 4;
   solve(n);
}

Input

4

Output

()()()()
(())()()
((()))()
(((())))

Updated on: 03-Mar-2022

332 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements