-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathGenerate_Paranthesis.cpp
More file actions
47 lines (39 loc) · 1014 Bytes
/
Generate_Paranthesis.cpp
File metadata and controls
47 lines (39 loc) · 1014 Bytes
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
// Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
// Example 1:
// Input: n = 3
// Output: ["((()))","(()())","(())()","()(())","()()()"]
// Example 2:
// Input: n = 1
// Output: ["()"]
// Constraints:
// 1 <= n <= 8
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> answer;
string s="";
generate(s,n,n,answer);
return answer;
}
void generate(string &s,int open,int close,vector<string> &answer){
if(open==0 and close==0)
{
answer.push_back(s);
return;
}
if(open>0)
{
s.push_back('(');
generate(s,open-1,close,answer);
s.pop_back();
}
if(close>0){
if(open<close)
{
s.push_back(')');
generate(s,open,close-1,answer);
s.pop_back();
}
}
}
};