TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
generate_parentheses.cpp
Go to the documentation of this file.
1
14#include <cassert>
15#include <iostream>
16#include <vector>
17
22namespace backtracking {
27 private:
28 std::vector<std::string> res;
29
30 void makeStrings(std::string str, int n, int closed, int open);
31
32 public:
33 std::vector<std::string> generate(int n);
34};
35
45void generate_parentheses::makeStrings(std::string str, int n,
46 int closed, int open) {
47 if (closed > open) // We can never have more closed than open
48 return;
49
50 if ((str.length() == 2 * n) &&
51 (closed != open)) { // closed and open must be the same
52 return;
53 }
54
55 if (str.length() == 2 * n) {
56 res.push_back(str);
57 return;
58 }
59
60 makeStrings(str + ')', n, closed + 1, open);
61 makeStrings(str + '(', n, closed, open + 1);
62}
63
70std::vector<std::string> generate_parentheses::generate(int n) {
72 std::string str = "(";
74 return res;
75}
76} // namespace backtracking
77
82static void test() {
83 int n = 0;
84 std::vector<std::string> patterns;
86
87 n = 1;
88 patterns = {{"()"}};
89 assert(p.generate(n) == patterns);
90
91 n = 3;
92 patterns = {{"()()()"}, {"()(())"}, {"(())()"}, {"(()())"}, {"((()))"}};
93
94 assert(p.generate(n) == patterns);
95
96 n = 4;
97 patterns = {{"()()()()"}, {"()()(())"}, {"()(())()"}, {"()(()())"},
98 {"()((()))"}, {"(())()()"}, {"(())(())"}, {"(()())()"},
99 {"(()()())"}, {"(()(()))"}, {"((()))()"}, {"((())())"},
100 {"((()()))"}, {"(((())))"}};
101 assert(p.generate(n) == patterns);
102
103 std::cout << "All tests passed\n";
104}
105
110int main() {
111 test(); // run self-test implementations
112 return 0;
113}
std::vector< std::string > res
Contains all possible valid patterns.
void makeStrings(std::string str, int n, int closed, int open)
function that adds parenthesis to the string.
std::vector< std::string > generate(int n)
wrapper interface
static void test()
Self-test implementations.
int main()
Main function.
for vector container