Unique Binary Search Trees
2015-08-03 15:20
691 查看
Given n, how many structurally unique binary search trees that store values 1...n?
For example,
Given n = 3, there are a total of 5 unique BST's.
num[i]表示i的二叉搜索树的个数. 它的数目是由子树有多少不同的根结点决定的.
For example,
i=0, count[0]=1 //empty tree
i=1, count[1]=1 //one tree
i=2, count[2]=count[0]*count[1] // 0 is root
+ count[1]*count[0] // 1 is root
i=3, count[3]=count[0]*count[2] // 1 is root
+ count[1]*count[1] // 2 is root
+ count[2]*count[0] // 3 is root
i=4, count[4]=count[0]*count[3] // 1 is root
+ count[1]*count[2] // 2 is root
+ count[2]*count[1] // 3 is root
+ count[3]*count[0] // 4 is root
..
i=n, count
= sum(count[0..k]*count[k+1...n]) 0 <= k < n-1
可以用动态规划来解决。
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
num[i]表示i的二叉搜索树的个数. 它的数目是由子树有多少不同的根结点决定的.
For example,
i=0, count[0]=1 //empty tree
i=1, count[1]=1 //one tree
i=2, count[2]=count[0]*count[1] // 0 is root
+ count[1]*count[0] // 1 is root
i=3, count[3]=count[0]*count[2] // 1 is root
+ count[1]*count[1] // 2 is root
+ count[2]*count[0] // 3 is root
i=4, count[4]=count[0]*count[3] // 1 is root
+ count[1]*count[2] // 2 is root
+ count[2]*count[1] // 3 is root
+ count[3]*count[0] // 4 is root
..
i=n, count
= sum(count[0..k]*count[k+1...n]) 0 <= k < n-1
可以用动态规划来解决。
public int numTrees(int n) { int[] num=new int[n+1]; num[0]=1; num[1]=1; for(int i=2;i<=n;i++){ for(int j=0;j<=i-1;j++) num[i]+=num[j]*num[i-j-1]; } return num ; }
相关文章推荐
- [折半枚举] poj 2785 4 Values whose Sum is 0
- 改变UISearchBar的细节问题
- hdu 4027 Can you answer these queries?
- POJ 2442 Sequence(堆的应用)
- HDU 4343 Interval query 倍增思想, DP
- UILabel自适应
- Flash Builder常见菊紧问题集锦
- 再谈select, iocp, epoll,kqueue及各种I/O复用机制
- iOS开发UI篇—简单介绍静态单元格的使用
- EasyUI Tree onLoadSuccess Data数据不正确
- iOS开发系列--UITableView全面解析
- 胡阳pyhton作业题--20150730
- js中return false,return,return true的用法及区别
- 自定义UISlider
- flask中的request对象方法
- 对Django框架架构和Request/Response处理流程的分析
- iOS开发UI篇—UIWindow简单介绍
- iOS开发UI篇—UITableview控件使用小结
- Daikon Forge GUI Library(dfgui)之地图制作并定位
- UIKit Dynamics 教程:抛掷 Views