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:
int numTrees(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n==0)
return 1;
else{
int num=0;
for(int i=0 ; i<n ; i++)
num+=numTrees(i)*numTrees(n-i-1);
return num;
}
}
};
如果想做一个非递归的,就用动态规划去做,代码如下:
class Solution {
public:
int numTrees(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int (*p)[2]=new int[n+1][2];
memset(p,0,sizeof(int)*(n+1)*2);
int num;
p[0][0]=1;
p[0][1]=1;
for(int i=1 ; i<=n ; i++){
num=0;
for(int j=0 ; j<i ; j++)
num+=p[j][0]*p[i-j-1][1];
p[i][0]=num;
p[i][1]=num;
}
return p[n][0];
}
};效率比递归的要高很多很多!!
本文介绍了如何使用递归和动态规划两种方法解决计算不同数量的二叉搜索树的问题,并提供了高效算法实现的代码。
1444

被折叠的 条评论
为什么被折叠?



