-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenerate_Parentheses.cpp
69 lines (55 loc) · 1.34 KB
/
Generate_Parentheses.cpp
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Clavius, the person who suggested grouping of data using brackets.
// He has suggested that the group of brackets should be Well-Formed.
// A string is said to be Well-Formed, if:
// - The string is empty.
// - The string can be written as MN, (M is appended to N),
// where M and N are Well-Formed Strings, or
// - The string can be written as {M}, where M is Well-Formed string.
// You will be given an integer N. Your task is to return the list of all
// Well-Formed strings of length 2*N.
// Input Format:
// -------------
// An integer N.
// Output Format:
// --------------
// Print the list of well-formed strings.
// Sample Input-1:
// ---------------
// 3
// Sample Output-1:
// ----------------
// [{{{}}},{{}{}},{{}}{},{}{{}},{}{}{}]
// Sample Input-2:
// ---------------
// 1
// Sample Output-2:
// ----------------
// [{}]
#include<bits/stdc++.h>
using namespace std;
vector<string> res;
void solve(int n,string x,int open,int close){
if(x.size()==2*n){
res.push_back(x);
return;
}
if(open<n){
x=x+"{";
solve(n,x,open+1,close);
x.pop_back();
}
if(close<open){
x=x+"}";
solve(n,x,open,close+1);
x.pop_back();
}
}
int main(){
int n;
cin>>n;
string x="";
solve(n,x,0,0);
for(auto i:res){
cout<<i<<" ";
}
}