Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
For example,
Given n = 3, there are a total of 5 unique BST's.
1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
Solution:
Similar to #95.
Code:
class Solution {
public:
int numTrees(int n) {
vector<vector<int>> dp(n,vector<int>(n,-1));
return calNum(1,n,dp);
}
int calNum(int start, int end, vector<vector<int>> &dp){
int res = 0;
if(start > end) return 1;
if(dp[start-1][end-1] != -1) return dp[start-1][end-1];
for(int rootval = start; rootval <= end; rootval++){
int left = calNum(start, rootval-1,dp);
int right = calNum(rootval+1, end,dp);
res +=left*right;
}
dp[start-1][end-1] = res;
return res;
}
};