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.
class Solution {
public:
int numTrees(int n) {
//递归思想,f(i)=f(i-1)*f(n-i);
//从1到n作根结点,计算种数然后累加起来。但是此解法超时
//只能放弃递归调用本函数的想法,用数组实现
int count1[n+1];
count1[0]=1;
count1[1]=1;
//构造出一个数组,第n个元素为所求值
for(int i=2;i<=n;i++)
{
count1[i]=0; //没有初始化导致错误
for (int j=1;j<=i;j++) //求出2到n的每个元素值
{
count1[i]+=count1[j-1] * count1[i-j]; //事先做好初始化0准备
}
}
return count1[n];
}
};
下面附上递归调用函数的解法(超时):
class Solution {
public:
int numTrees(int n) {
int count1=0;
if (n<=0||n==1)
{return 1;}
for (int i=1;i<=n;i++)
{ //递归思想,f(i)=f(i-1)*f(n-i);
//从1到n作根结点,计算种数然后累加起来。但是此解法超时
count1+=numTrees(i-1)*numTrees(n-i);
}
return count1;
}
};