Valid Parentheses
/***
9.6
Implement an algorithm to prink all valid (eg. properly opened and closed combinations of n-pairs of parentheses)
EXAMPLE:
input: 3
Output: ()()(), ((())), ()(()), (()()), (())()
***/
#include<iostream>
#include<set>
#include <string>
using namespace std;
void validParentheses(int n, set<string> *prt) {
if(n==0) return;
if (prt->empty())
{
string s;
s.push_back('(');
s.push_back(')');
prt->insert(s);
} else {
set<string> ts;
set<string> :: iterator it;
ts = *prt;
prt->clear();
for(it = ts.begin(); it != ts.end(); it++) {
string s = *it;
string :: iterator it1, it2;
for(int i=0; i<s.size(); i++) {
if(s[i] == '(') {
s.insert(i, "(");
string temp = s;
for(int j=i+1; j<s.size(); j++) {
if(temp[j] == ')') {
temp = s;
temp.insert(j+1, ")");
prt->insert(temp);
}
}
}
s = *it;
}
s.push_back('(');
s.push_back(')');
prt->insert(s);
}
}
validParentheses(n-1, prt);
}
void main() {
int n = 3;
set<string> partset;
set<string> :: iterator it;
validParentheses(n, &partset);
for (it = partset.begin(); it != partset.end(); it++)
{
cout<<*it<<endl;
}
}
Comments
Post a Comment