-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path22.generate-parentheses.cpp
More file actions
48 lines (39 loc) · 1.1 KB
/
22.generate-parentheses.cpp
File metadata and controls
48 lines (39 loc) · 1.1 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
#include "testharness.h"
#include <cassert>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
if (n == 0) return result;
string buffer(n * 2, '0');
doGenerateParenthesis(n, 0, 0, buffer, result);
return result;
}
private:
void doGenerateParenthesis(int n, int p, int q, string& buffer, vector<string>& result) {
assert(p >= q);
if (p == n) {
for (int i = p + q; i < 2 * n; i++)
buffer[i] = ')';
result.push_back(buffer);
return;
}
int next = p + q;
if (p > q) {
buffer[next] = ')';
doGenerateParenthesis(n, p, q+1, buffer, result);
}
buffer[next] = '(';
doGenerateParenthesis(n, p+1, q, buffer, result);
}
};
TEST(Solution, test) {
auto result = generateParenthesis(3);
for (auto iter = result.begin(); iter != result.end(); ++iter)
std::cout << *iter << std::endl;
ASSERT_EQ(2, 1+1);
}