-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerateParenthesis.cpp
More file actions
54 lines (53 loc) · 1.17 KB
/
generateParenthesis.cpp
File metadata and controls
54 lines (53 loc) · 1.17 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
49
50
51
52
53
54
// recursion
class Solution {
public:
void add (int n) {
if (cache.find(n) != cache.end())
return;
for (int i = 0; i < n; ++i) {
add(i);
add(n - 1 - i);
for (auto &s1: cache[i]) {
for (auto &s2: cache[n - 1 - i]) {
cache[n].push_back("(" + s1 + ")" + s2);
}
}
}
}
vector<string> generateParenthesis(int n) {
cache.clear();
cache[0] = {""};
cache[1] = {"()"};
add(n);
return cache[n];
}
private:
unordered_map<int, vector<string> > cache;
};
// dfs
class Solution {
public:
void dfs (int idx, int l, int r) {
if (!l && !r) {
ans.push_back(single);
return;
}
if (l) {
single[idx] = '(';
dfs(idx + 1, l - 1, r);
}
if (r && r > l) {
single[idx] = ')';
dfs(idx + 1, l, r - 1);
}
}
vector<string> generateParenthesis(int n) {
ans.clear();
single.resize(2 * n);
dfs(0, n, n);
return ans;
}
private:
string single;
vector<string> ans;
};