1+ /* *
2+ * @file
3+ * @brief Generates all combinations of well-formed parentheses.
4+ *
5+ * @details a sequence of parentheses is well-formed if each opening parentheses
6+ has a corresponding closing parenthesis
7+ * and the closing parentheses are correctly ordered
8+ *
9+ * @author [Giuseppe Coco](https://github.com/WoWS17)
10+
11+ */
12+
13+ #include < cassert>
14+ #include < iostream>
15+ #include < vector>
16+
17+ class generate_parentheses {
18+ private:
19+ std::vector<std::string> res; // Contains all possible valid patterns
20+
21+ /* *
22+ * @brief function that implements backtracking
23+ *
24+ * @param str string build during backtracking
25+ * @param n number of pairs of parentheses
26+ * @param closed number of closed parentheses
27+ * @param open number of open parentheses
28+ */
29+
30+ void makeStrings (std::string str, int n, int closed, int open) {
31+ if (closed > open) // We can never have more closed than open
32+ return ;
33+
34+ if (str.length () == 2 * n and
35+ closed != open) // closed and open must be the same
36+ return ;
37+
38+ if (str.length () == 2 * n) {
39+ res.push_back (str);
40+ return ;
41+ }
42+
43+ makeStrings (str + ' )' , n, closed + 1 , open);
44+ makeStrings (str + ' (' , n, closed, open + 1 );
45+ }
46+
47+ public:
48+ /* *
49+ * @brief wrapper interface
50+ *
51+ * @param n number of pairs of parentheses
52+ * @return all well-formed pattern of parentheses
53+ */
54+ std::vector<std::string> generate_parenthesis (int n) {
55+ res.clear ();
56+ std::string str = " (" ;
57+ makeStrings (str, n, 0 , 1 );
58+ return res;
59+ }
60+ };
61+
62+ /* *
63+ * @brief Self-test implementations
64+ * @returns void
65+ */
66+ static void test () {
67+ int n;
68+ std::vector<std::string> patterns;
69+ generate_parentheses p;
70+
71+ n = 1 ;
72+ patterns = {{" ()" }};
73+ assert (p.generate_parenthesis (n) == patterns);
74+
75+ n = 3 ;
76+ patterns = {{" ()()()" }, {" ()(())" }, {" (())()" }, {" (()())" }, {" ((()))" }};
77+
78+ assert (p.generate_parenthesis (n) == patterns);
79+
80+ n = 4 ;
81+ patterns = {{" ()()()()" }, {" ()()(())" }, {" ()(())()" }, {" ()(()())" },
82+ {" ()((()))" }, {" (())()()" }, {" (())(())" }, {" (()())()" },
83+ {" (()()())" }, {" (()(()))" }, {" ((()))()" }, {" ((())())" },
84+ {" ((()()))" }, {" (((())))" }};
85+ assert (p.generate_parenthesis (n) == patterns);
86+
87+ std::cout << " All tests passed\n " ;
88+ }
89+
90+ /* *
91+ * @brief Main function
92+ * @returns 0 on exit
93+ */
94+ int main () {
95+ test ();
96+ return 0 ;
97+ }
0 commit comments