Generate all the combinations of well formed parentheses || in cpp solution

 



#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

void solve(vector<string> &ans, int open, int close, string s, int n)
{
    if (s.size() == 2 * n)
    {
        ans.push_back(s);
        return;
    }
    if (open < n)
    {
        solve(ans, open + 1, close, s + '(', n);
    }
    if (close < open)
    {
        solve(ans, open, close + 1, s + ')', n);
    }
}

vector<string> generete(int n)
{
    vector<string> ans;
    solve(ans, 0, 0, "", n);
    return ans;
}

int main()
{

    int n ;

cin>>n;
    vector<string> ans = generete(n);

    sort(ans.begin(), ans.end());
    cout << "{ ";
    for (int i = 0; i < ans.size(); i++)
    {
        cout << ans[i] << ", ";
    }
    cout << "}";
}

Post a Comment

0 Comments