leetcode:Unique Binary Search Trees
2024-10-16 10:47:48
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
注意:二分查找树的定义是,左子树节点均小于root,右子树节点均大于root!不要想当然地将某个点作为root时,认为其他所有节点都能全部放在left/right中,除非这个点是 min 或者 max 的。
分析:本题其实关键是递推过程的分析,n个点中每个点都可以作为root,当 i 作为root时,小于 i 的点都只能放在其左子树中,大于 i 的点只能放在右子树中,此时只需求出左、右子树各有多少种,二者相乘即为以 i 作为root时BST的总数。
开始时,我尝试用递归实现,但是超时了,可见系统对运行时间有要求。因为递归过程中存在大量的重复计算,从n一层层往下递归,故考虑类似于动态规划的思想,让底层的计算结果能够被重复利用,故用一个数组存储中间计算结果(即 1~n-1 对应的BST数目),这样只需双层循环即可,代码如下:
class Solution {
public:
int numTrees(int n) {
vector<int> num;
num.push_back(1); //在容器尾端插入一项数据,设置num[0]=1
for(int i=1; i<=n; i++){
num.push_back(0); //每次先将num[i]设置为0
if(i<3)
num[i]=i; //易知num[1]=1,num[2]=2
else{
for(int j=1; j<=i; j++)
num[i]+=num[j-1]*num[i-j]; //j为root节点,其左子树种数为j-1,右子树种数为i-j
}
}
return num[n];
}
};
其他解法:
1、1ms in C++ By Using Theorem From Graph Theory
This is my code. I use the property that the number of unique binary trees or n vertex is
{(2n)(2n-1)(2n-2)....(n+2)}/{(n)(n-1)....(2)(1)}
class Solution {
public:
int numTrees(int n) {
long long result = 1;
long long temp = 1;
for(int i = 2*n; i > n; i--){
result *= i;
temp *= (i-n);
if (result % temp == 0){
result /= temp;
temp = 1;
}
}
return result/(n+1);
}
};
2、2ms c++ using dp(动态规划)
class Solution {
public:
int numTrees(int n){
int arr[n+1][n+1];
memset(arr,0,sizeof(arr));
for(int len=1; len<=n; len++){
for(int j=1; j<=n-len+1; j++){
if(len == 1) arr[len][j] = 1;
else{
arr[len][j] += arr[len-1][j+1];
arr[len][j] += arr[len-1][j];
for(int k=1;k<len;k++) arr[len][j] += (arr[k][j]*arr[len-k-1][j+k+1]);
}
}
}
return arr[n][1];
}
};
3、
class Solution {
public:
int numTrees(int n) {
if(n==0) return 0;
int s[n+1];
int r;
s[0] = 1;
for(int i=1; i<n+1; i++)
{
s[i] = 0;
for(int l=0; l<i; l++)
{
r = i-1-l;
s[i] = s[i]+s[l]*s[r];
}
}
return s[n];
}
};
最新文章
- 如何设计一个优秀的API(转载)
- 解迷宫的C++的未完善编程代码........请大神们帮忙改善下.........
- Sqlite日期类型问题:该字符串未被识别为有效的 DateTime(String not recognized as a valid datetime)
- phpcms 05
- Android 框架修炼-自己封装双缓存管理框架库
- 手把手教你Windows下Go语言的环境搭建
- 算法-KMP模式匹配算法
- flume学习安装
- 使用 VMAccess 扩展程序重置 Linux 虚拟机的登录凭据
- QT中窗口刷新事件的学习总结
- Rotate It !!(思维)
- javascript模板引擎template.render使用
- oracle存储过程返回结果集
- Mock拦截ajax请求
- insert into select的实际用法
- StatefulSet(一):拓扑状态
- ORACLE 内置函数之 GREATEST 和 LEAST(转)
- Drying POJ - 3104 二分 最优
- matplotlib显示中文异常处理
- Android sdk content loader 0%