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
其实就是把新节点插入到前面所有节点位置的可能性的和
每次插入一个位置产生左树右树相乘 然后所有位置求和。
int numTrees(int n) {
int *dp = malloc(sizeof(int)*n+2);
dp[0]=1;
int i = 1;
int j = 1;
for (i = 1;i <=n; i++)
{
if(i<3)
{
dp[i]=i;
}
else
{
for(j = 1;j <= i;j++)
{
dp[i] += dp[j-1]*dp[i-j];
}
}
}
return dp[n];
}