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
Analysis: Just recursively count the number of left sub tree times number of right sub tree.
class Solution {
public:
int calculate(int n){
int sum = ;
for(int i = ; i< n ;i++ )
sum += tree[i] * tree[n--i] ;
// tree[i] : left subTree tree[n-1-i] " right subTree
return sum ;
}
int numTrees(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
tree.resize(n+,);
for(int i = ; i <= n ; i++)
tree[i] = calculate(i);
return tree[n] ; }
private :
vector<int> tree;
};