forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
45 lines (31 loc) · 771 Bytes
/
main.cpp
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
/// Source : https://leetcode.com/problems/unique-binary-search-trees/description/
/// Author : liuyubobobo
/// Time : 2018-09-10
#include <iostream>
#include <vector>
using namespace std;
/// Memory Search
/// Time Complexity: O(n)
/// Space Complexity: O(n)
class Solution {
public:
int numTrees(int n) {
vector<int> dp(n + 1, -1);
return numTrees(n, dp);
}
private:
int numTrees(int n, vector<int>& dp){
if(n <= 1)
return 1;
if(dp[n] != -1)
return dp[n];
int res = 0;
for(int i = 1; i <= n; i ++)
res += numTrees(i - 1, dp) * numTrees(n - i, dp);
return dp[n] = res;
}
};
int main() {
cout << Solution().numTrees(3) << endl;
return 0;
}