96. Unique Binary Search Trees
2016-06-07 20:33
489 查看
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.
分析摘自:http://www.tuicool.com/articles/NRjmyyI
代码摘自:http://www.tuicool.com/articles/IFZbAr
注意BST的性质,左子树元素<根元素<右子树元素
如果集合为空,只有一种BST,即空树,
UniqueTrees[0] =1
如果集合仅有一个元素,只有一种BST,即为单个节点UniqueTrees[1] = 1
UniqueTrees[2] = UniqueTrees[0] * UniqueTrees[1] (1为根的情况,左子树挂0个右子树挂1个)+ UniqueTrees[1] * UniqueTrees[0] (2为根的情况,左子树挂1个右子树挂0个)。
再看一遍三个元素的数组,可以发现BST的取值方式如下:
UniqueTrees[3] = UniqueTrees[0]*UniqueTrees[2] (1为根的情况,左子树挂0个右子树挂2个)
+ UniqueTrees[1]*UniqueTrees[1] (2为根的情况,左子树挂1个右子树挂1个)
+ UniqueTrees[2]*UniqueTrees[0] (3为根的情况,左子树挂2个右子树挂0个)
所以,由此观察,可以得出UniqueTrees的递推公式为UniqueTrees[i] = ∑ UniqueTrees[k] * [i-1-k] k取值范围 0<= k <=(i-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
分析摘自:http://www.tuicool.com/articles/NRjmyyI
代码摘自:http://www.tuicool.com/articles/IFZbAr
注意BST的性质,左子树元素<根元素<右子树元素
如果集合为空,只有一种BST,即空树,
UniqueTrees[0] =1
如果集合仅有一个元素,只有一种BST,即为单个节点UniqueTrees[1] = 1
UniqueTrees[2] = UniqueTrees[0] * UniqueTrees[1] (1为根的情况,左子树挂0个右子树挂1个)+ UniqueTrees[1] * UniqueTrees[0] (2为根的情况,左子树挂1个右子树挂0个)。
再看一遍三个元素的数组,可以发现BST的取值方式如下:
UniqueTrees[3] = UniqueTrees[0]*UniqueTrees[2] (1为根的情况,左子树挂0个右子树挂2个)
+ UniqueTrees[1]*UniqueTrees[1] (2为根的情况,左子树挂1个右子树挂1个)
+ UniqueTrees[2]*UniqueTrees[0] (3为根的情况,左子树挂2个右子树挂0个)
所以,由此观察,可以得出UniqueTrees的递推公式为UniqueTrees[i] = ∑ UniqueTrees[k] * [i-1-k] k取值范围 0<= k <=(i-1)
public int numTrees(int n) { if(n<=0) return 0; int[] res = new int[n+1]; res[0] = 1; res[1] = 1; for(int i=2;i<=n;i++) { for(int j=0;j<i;j++) { res[i] += res[j]*res[i-j-1]; } } return res ; }
相关文章推荐
- EasyUI datagrid在Layout中动态适应问题
- Adafruit公司2015年最棒的开源可穿戴设备
- GCD之dispatch queue深入浅出
- 云计算--在bluemix平台上部署一个JavaWeb程序
- POJ 1141 Brackets Sequence 区间dp
- Codeforces #353 (div2)A. Infinite Sequence
- BZOJ 1670 [Usaco2006 Oct]Building the Moat护城河的挖掘
- iOS setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key 问题
- View requires API level 14 (current min is 8): <GridLayout>的解决方法-
- 用Mockplus教你使用属性面板的设置交互状态
- UISearchController Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior
- 用任务管理器关闭客户端后,服务器的早先投递的WSARecv没有从GetQueuedCompletionStatus返回
- iOS开发UI基础—手写控件,frame,center和bounds属性
- UIBezierPath + CAShapeLayer的简单使用
- ndk错误解决方法 ndk-build NDK_PROJECT_PATH
- iOS UIButton实现上显示图片,下显示文字
- HDU 1242 Rescue (BFS+优先队列)
- 3D角色遮挡住UI的实现,关于Stencil Buffer,描边,以及其他
- 11572 - Unique Snowflakes
- easyUI combox 省市县3级联动