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这个题因为只需要计算结果数据,所以用dp就行。
公式:f[i] += f[i-j] * f[j-1];
分别代表左子树和右子树的数量。
int numTrees(int n) {
if(n == 0||n==1) return 1;
int f[n+1],i,j;
memset(f,0,sizeof(f));
f[0] = 1;
f[1] = 1;
for(i = 2; i <= n; i++)
{
for(j = 1 ; j <= i; j++)
{
f[i] += f[i-j] * f[j-1];
}
}
return f[n];
}