Unique Binary Search Trees
2016-06-01 15:05
453 查看
题目描述:
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.
我是先做的Unique Binary Search Trees II,然后用那个方法递归,超时了,应该用动态规划的方法。
递归方法代码如下:(超时!)
public int numTrees(int n) {
return getNum(1, n);
}
public int getNum(int left,int right){
int result=0;
if(left>=right)
return 1;
for(int i=left;i<=right;i++){
int leftnum=getNum(left, i-1);
int rightnum=getNum(i+1, right);
result+=leftnum*rightnum;
}
return result;
}AD代码如下:
public static int numTrees(int n) {
int[] cnt = new int[n+1];
cnt[0] = 1;
cnt[1] = 1;
for(int i=2; i<=n; i++){
for(int j=0; j<=i-1; j++){
cnt[i] += cnt[j] * cnt[i-1-j];
}
}
return cnt
;
}
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
我是先做的Unique Binary Search Trees II,然后用那个方法递归,超时了,应该用动态规划的方法。
递归方法代码如下:(超时!)
public int numTrees(int n) {
return getNum(1, n);
}
public int getNum(int left,int right){
int result=0;
if(left>=right)
return 1;
for(int i=left;i<=right;i++){
int leftnum=getNum(left, i-1);
int rightnum=getNum(i+1, right);
result+=leftnum*rightnum;
}
return result;
}AD代码如下:
public static int numTrees(int n) {
int[] cnt = new int[n+1];
cnt[0] = 1;
cnt[1] = 1;
for(int i=2; i<=n; i++){
for(int j=0; j<=i-1; j++){
cnt[i] += cnt[j] * cnt[i-1-j];
}
}
return cnt
;
}
相关文章推荐
- UITableView优化——UITableViewCell高度的优化
- UITableView优化——UITableViewCell高度的优化
- UIView加任意边框(Masonry)
- 关于(UITableViewcell)contentView高度的问题
- 为什么设置了view的Opaque性能会提高(GPU)
- 二叉树的层序遍历
- Solr --- Query
- Unique Binary Search Trees II
- iOS UIBezierPath图形绘制
- SUID和SGID位简介
- Geometry cannot have Z values.
- org.hibernate.QueryException:Expected positional parameter count: 1
- UIScrollView的PageEnable可以实现slider
- Import Project...出现 Building 'xxxx' Gradle project info会卡半天,完美解决
- 斐波那契数列-Fibonacci Sequence
- LTE UE不活动定时器的工作机制
- 监听UITextField内容改变简单方法
- Uedit32和Ubuntu 选定跳转
- 关于xib中要TableviewCell的自定义心得
- 动态加载HTML后使用query修改标签样式