LeetCode96_Unique Binary Search Trees(求1到n这些节点可以组成多少种不同的二叉查找树) Java题解
2015-08-20 14:19
603 查看
题目:
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.
解题:
用递归的思想,当只有0个或是1个节点的时候,只有一种;n个节点的时候有f(n)种:
左边可以有n-1个节点,右边0个节点,根据对称性可以左右互换,这时候有2*f(n-1)*f(0);
一边1个,另一边n-2个,这时候有2*f(1)*f(n-2);
一边两个,一边N-3个,这时候有2*f(2)*f(n-3);
。。。。。。
如果n为奇数,两边都是n/2个,这时候有f(n/2)*f(n/2),如果n为偶数,一边n/2一边(n/2+1)个,为2*f(n/2)*f(n/2+1);
代码:
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
解题:
用递归的思想,当只有0个或是1个节点的时候,只有一种;n个节点的时候有f(n)种:
左边可以有n-1个节点,右边0个节点,根据对称性可以左右互换,这时候有2*f(n-1)*f(0);
一边1个,另一边n-2个,这时候有2*f(1)*f(n-2);
一边两个,一边N-3个,这时候有2*f(2)*f(n-3);
。。。。。。
如果n为奇数,两边都是n/2个,这时候有f(n/2)*f(n/2),如果n为偶数,一边n/2一边(n/2+1)个,为2*f(n/2)*f(n/2+1);
代码:
public static int numTrees(int n) { if(n==1||n==0) return 1; int sum=0; if(n%2==0) { for(int k=n-1;k>=n/2;k--) { sum+=2*numTrees(k)*numTrees(n-1-k); } return sum; } else { for(int k=n-1;k>n/2;k--) { sum+=2*numTrees(k)*numTrees(n-1-k); } return sum+numTrees(n/2)*numTrees(n/2); } }
相关文章推荐
- UISegmentControl的属性和方法
- UITableView滑动删除学习笔记
- UI架构设计的演化
- iOS多线程——NSOperation & NSOperationQueue
- List<NameValuePair> params = new ArrayList<NameValuePair>();
- php:$_REQUEST、$_POST、$_GET的区别和联系
- ios uitableview header不随着滚动
- The Unique MST
- requireJS简单的学习门户网站
- 开源作品-PHP写的在线文件管理工具(单文件绿色版)-SuExplorer_PHP_2_0
- QSqlQueryModel读取数据库,提示 database locked
- 搞定百度编辑器UEditor
- 在UINavigation上添加UISearchBar
- 虚拟化--004 your account is no authorized to perform the requested action
- UITableViewCell的重用问题
- IOS开发 - UIApplication的常见使用
- UE4 GPU Profiling
- UE4 CPU Profiling
- UE4 Profiler
- UE4 Performance Guidelines