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
class Solution {
public:
/*algorithm dp solution
assume tree has n nodes, left tree has j nodes, right tree has n-1-j nodes
c(0) = 1
c(1) = c(0)c(0) = 1
c(n) = c(0)c(n-1) + c(1)c(n-2)+...+c(n-1)c(0)
time O(n) space O(n)
*/
int numTrees(int n) {
vector<int>c(n+1,0);
c[0] = 1;
for(int i = 1;i < n+1;i++){
for(int j = 0;j < i;j++)
c[i] += c[j]*c[i-1-j];
}
return c[n];
}
};