problem
solution
1 | /** |
- memo pattern
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
30class Solution {
public:
vector<vector<vector<TreeNode*>>> memo;
vector<TreeNode*> generateTrees(int l, int r){
if(l>r) return {nullptr};
if(!memo[l][r].empty()) return memo[l][r];
vector<TreeNode *> ret;
for(int i=l;i<=r;++i){
vector<TreeNode*> left = generateTrees(l, i-1);
vector<TreeNode*> right = generateTrees(i+1, r);
for(auto l:left){
for(auto r:right){
TreeNode *t = new TreeNode(i);
t->left = l;
t->right = r;
ret.push_back(t);
}
}
}
return memo[l][r] = ret;
}
vector<TreeNode*> generateTrees(int n) {
memo = vector<vector<vector<TreeNode * >>>(n+1, vector<vector<TreeNode*>>(n+1));
return generateTrees(1, n);
}
};analysis
- time complexity
O(n^2)