【Leetcode】:Unique Binary Search Trees
来源:互联网 发布:华为手机数据迁移 编辑:程序博客网 时间:2024/04/30 05:25
Unique Binary Search Trees
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的总数。
public class Solution {public int numTrees(int n) {
int[] count = new int[n+1];
count[0] = 1;
count[1] = 1;
for(int k=2;k<=n;k++)
{
count[k]=0;
for(int i=1;i<=k;i++)
{
count[k]=count[k]+count[i-1]*count[k-i];
}
}
return count[n];
}
}
0 0
- LeetCode: Unique Binary Search Trees
- LeetCode : Unique Binary Search Trees
- [Leetcode] Unique Binary Search Trees
- [LeetCode]Unique Binary Search Trees
- LeetCode Unique Binary Search Trees
- Leetcode: Unique Binary Search Trees
- LeetCode-Unique Binary Search Trees
- [leetcode] Unique Binary Search Trees
- LeetCode - Unique Binary Search Trees
- [LeetCode] Unique Binary Search Trees
- 【Leetcode】Unique Binary Search Trees
- Leetcode: Unique Binary Search Trees
- 【LeetCode】Unique Binary Search Trees
- Leetcode Unique Binary Search Trees
- Leetcode: Unique Binary Search Trees
- [LeetCode] Unique Binary Search Trees
- Leetcode: Unique Binary Search Trees
- LeetCode | Unique Binary Search Trees
- zoj 1311 poj 1144 Network(无向图顶点联通度)
- 解决ngui 粒子 层级显示问题
- 自学笔记之Quartz2D
- <Garry和图表第二次约会>HighCharts, Android传数据(可以不用ajax你造吗)
- C51中的关键字data,idata,xdata,pdata,bdata
- 【Leetcode】:Unique Binary Search Trees
- android手机桌面图标消失解决方法
- 深入Java集合学习系列:HashMap的实现原理
- 去除list中的重复对象
- 【Android】为什么Android的图片质量会比iPhone的差?
- Hibernate 实体类注解
- 深入Java集合学习系列:HashSet的实现原理
- ubuntu14.04配置个人笔记
- 整数划分