Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Find all combinations of well-formed brackets from a given paris of parentheses

C++ String: Exercise-17 with Solution

Write a C++ program to find all combinations of well-formed brackets from a given paris of parentheses.

Example-1:

Input: 2 (given paris of parentheses)

Output: [[]] [][]

Example-2:

Input: 3 (given paris of parentheses)

Output: [[]] [][] [[[]]] [[][]] [[]][] [][[]] [][][]

Sample Solution:

C++ Code:

#include <iostream>

#include<algorithm>
 
using namespace std;
vector<string> result;
void Parenthesis(int start_bracket, int close_bracket, string curr, int n)
{
    if(curr.size()==2*n)
    {
        result.push_back(curr);
        return;
    }
    if(start_bracket<n)
    {
        Parenthesis(start_bracket+1,close_bracket,curr+"[",n);
    }
    if(close_bracket<start_bracket)
    {
        Parenthesis(start_bracket,close_bracket+1,curr+"]",n);
    }
}
vector<string> generate_Parenthesis(int n) 
{
    Parenthesis(0, 0 ,"", n);
    return result;
} 
int main()
{
   int n;
   vector<string> result_Parenthesis;
   n = 2; 
   cout << "n = " << n << "\n"; 
   result_Parenthesis = generate_Parenthesis(n);   
   for (int i = 0; i < result_Parenthesis.size(); i++) {
        std::cout << result_Parenthesis.at(i) << ' ';
     }
   n = 3;
   cout << "\n\nn = " << n << "\n"; 
   result_Parenthesis = generate_Parenthesis(n);   
   for (int i = 0; i < result_Parenthesis.size(); i++) {
        std::cout << result_Parenthesis.at(i) << ' ';
     } 
   return 0;
}

Sample Output:

n = 2
[[]] [][]

n = 3
[[]] [][] [[[]]] [[][]] [[]][] [][[]] [][][]

Flowchart:

Flowchart: Find all combinations of well-formed brackets from a given paris of parentheses.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to find the longest common prefix from a given array of strings.

Next: Write a C++ programming to find the length of the longest valid (correct-formed) parentheses substring of a given string.

What is the difficulty level of this exercise?