forked from anmol098/algorithms_and_data_structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate_parenthesis.cpp
41 lines (36 loc) · 1007 Bytes
/
generate_parenthesis.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
/**
* Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
*
* For example, given n = 3, a solution set is:
*
* "((()))", "(()())", "(())()", "()(())", "()()()"
*
*/
#include <iostream>
#include <vector>
#include <string>
void generate_parenthesis_helper( int n, int left, int right, std::string curr, std::vector<std::string> & result ) {
if (right == n) {
result.push_back(curr);
} else {
if (left < n) {
generate_parenthesis_helper( n, left + 1, right, curr + '(', result);
}
if (right < left) {
generate_parenthesis_helper( n, left, right + 1, curr + ')', result);
}
}
}
std::vector<std::string> generate_parenthesis( int n ) {
std::vector<std::string> result;
std::string curr{ "" };
generate_parenthesis_helper(n, 0, 0, curr, result);
return result;
}
int main() {
std::vector<std::string> result = generate_parenthesis(3);
for ( auto s : result ) {
std::cout << "{ " << s << " }" << std::endl;
}
return 0;
}