-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0095-unique-binary-search-trees-ii.cpp
More file actions
57 lines (48 loc) · 1.5 KB
/
0095-unique-binary-search-trees-ii.cpp
File metadata and controls
57 lines (48 loc) · 1.5 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
55
56
57
#include<vector>
#include <string>
#include <unordered_map>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
explicit TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
right(right) {}
};
class Solution {
public:
vector<TreeNode *> recur(int n, int startFrom, unordered_map<string, vector<TreeNode*>> &memo) {
vector<TreeNode *> ans;
if (n <= 0){
ans.push_back(nullptr);
return ans;
}
string key = to_string(n) + "-" + to_string(startFrom);
if (memo.find(key) != memo.end()) {
return memo[key];
}
for (int i = 0; i < n; i++) {
auto lefts = recur(i, startFrom, memo);
auto rights = recur(n - i - 1, startFrom + i + 1, memo);
for (auto &left: lefts)
for (auto &right: rights) {
auto node = new TreeNode(startFrom + i);
node->left = left;
node->right = right;
ans.push_back(node);
}
}
memo[key] = ans;
return ans;
}
vector<TreeNode *> generateTrees(int n) {
unordered_map<string, vector<TreeNode*>> memo;
return recur(n, 1, memo);
}
};
int main() {
Solution s;
s.generateTrees(2);
}