forked from dhara04/cracking-the-coding-interview-c--
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nestedParenthesis
42 lines (39 loc) · 895 Bytes
/
nestedParenthesis
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<string>
#include<iostream>
#include<set>
using namespace std;
void nestedParenthesis(set<string>&paren, int n)
{
if(n == 1) {
paren.insert("()");
return;
}
nestedParenthesis(paren,n-1);
set<string> tempara;
for(set<string>::iterator it = paren.begin();it !=paren.end();it++ ){
string temp = *it;
tempara.insert("()"+ temp);
unsigned int i =0;
while(i<temp.length()){
if(temp[i] == '('){
tempara.insert(temp.substr(0,i+1)+"()"+temp.substr(i+1));
}
i++;
}
}
//for n=3 , the output is :((())), (() ()), (()) (), () (()), () () ()
paren.clear();
//copy tempara to paren
for(set<string>::iterator it = tempara.begin();it !=tempara.end();it++ ){
paren.insert(*it);
}
}
int main()
{
int n= 3;
set<string> paren;
nestedParenthesis(paren,n);
for(set<string>::iterator vit = paren.begin();vit != paren.end();vit++)
cout<<*vit<<endl;
return 0;
}