#include <bits/stdc++.h>
using namespace std;
// recursive function to find all valid strings
void findValid(string str, int index, int open, int close,
int pair, string cur, unordered_set<string> &res) {
// base case, if end of string is reached
if (index == str.size()) {
// check if all open and closed invalid
// parenthesis are removed and no pair is left
if (open == 0 && close == 0 && pair == 0) {
// if so, store the string
res.insert(cur);
}
return;
}
// if the current character is not a parenthesis
if (str[index] != '(' && str[index] != ')') {
// add the character to the current string
findValid(str, index + 1, open, close,
pair, cur + str[index], res);
}
else {
// if the current character is an open bracket
if (str[index] == '(') {
// reduce open count by 1,
// and skip current character
if (open > 0) {
findValid(str, index + 1, open - 1,
close, pair, cur, res);
}
// add the current character to the string
findValid(str, index + 1, open, close,
pair + 1, cur + str[index], res);
}
// else if the current character is a closed bracket
else {
// skip current character and
// reduce closed count by 1
if (close > 0)
findValid(str, index + 1, open,
close - 1, pair, cur, res);
// if there is an open pair, reduce
// it and add the current character
if (pair > 0)
findValid(str, index + 1, open, close,
pair - 1, cur + str[index], res);
}
}
}
vector<string> validParenthesis(string &str) {
// to store the unique valid strings
unordered_set<string> result;
// to store count of invalid
// open and closed paraenthesis
int open = 0, close = 0;
// count the number of invalid
// open and closed parenthesis
for (auto c : str) {
// if open bracket, increase
// open invalid count by 1
if (c == '(')
open++;
// if closed bracket,
if (c == ')') {
// decrement invalid open
// count by 1 if open is not 0
if (open != 0)
open--;
// else increment invalid closed
// bracket count by 1
else
close++;
}
}
// recursive function to find all valid strings
findValid(str, 0, open, close, 0, "", result);
// store the unique strings in an array
vector<string> res(result.begin(), result.end());
return res;
}
int main() {
string str = "(v)())()";
vector<string> res = validParenthesis(str);
for (string s : res) {
cout << s << endl;
}
return 0;
}