力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
class Solution {
public:
int numTrees(int n) {
std::vector<int> visited(n+1, -1);
return dfs(n, visited);
}
private:
int dfs(int n, std::vector<int>& visited) {
if (n == 0 || n == 1) {
return 1;
}
if (visited[n] != -1) {
return visited[n];
}
int result = 0;
for (int i = 1; i <= n; ++i) {
int tmp = dfs(i-1, visited) * dfs(n-i, visited);
result += tmp;
}
visited[n] = result;
return result;
}
};