-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_Parentheses.cpp
More file actions
55 lines (45 loc) · 1.13 KB
/
Copy pathgenerate_Parentheses.cpp
File metadata and controls
55 lines (45 loc) · 1.13 KB
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
/*
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Input: n = 1
Output: ["()"]
*/
#include<iostream>
#include<vector>
#include<string>
using namespace std;
void deal(string arr, int leftNum, int rightNum, vector<string>& allParent){
if(!leftNum && !rightNum){
allParent.push_back(arr);
return;
}
if(leftNum == rightNum){
arr.push_back('(');
deal(arr, leftNum-1, rightNum, allParent);
}
else if(leftNum == 0){
arr.push_back(')');
deal(arr, leftNum, rightNum-1, allParent);
}
else{
string arr1 = arr;
string arr2 = arr;
arr1.push_back('(');
deal(arr1, leftNum-1, rightNum, allParent);
arr2.push_back(')');
deal(arr2, leftNum, rightNum-1, allParent);
}
}
int main(){
int n = 0;
cin >> n;
int leftNum = n, rightNum = n;
string arr;
vector<string> allParent;
deal(arr, leftNum, rightNum, allParent);
for(auto i: allParent){
cout << i << " ";
}
return 0;
}