different/Unique/distinct Binary Search Trees
2015-09-16 15:24
447 查看
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
SOLUTION:
比如,以1为根的树有几个,完全取决于有二个元素的子树有几种。同理,2为根的子树取决于一个元素的子树有几个。以3为根的情况,则与1相同。 定义Count[i] 为以[0,i]能产生的Unique Binary Tree的数目, 如果数组为空,毫无疑问,只有一种BST,即空树, Count[0] =1 如果数组仅有一个元素{1},只有一种BST,单个节点 Count[1] = 1 如果数组有两个元素{1,2}, 那么有如下两种可能 1 2 \ / 2 1 Count[2] = Count[0] * Count[1] (1为根的情况) + Count[1] * Count[0] (2为根的情况。 再看一遍三个元素的数组,可以发现BST的取值方式如下: Count[3] = Count[0]*Count[2] (1为根的情况) + Count[1]*Count[1] (2为根的情况) + Count[2]*Count[0] (3为根的情况)
public int numTrees(int n) { int[] count = new int[n+1]; count[0] =1; count[1] =1; for(int i =2; i<=n; i++){ for(int j =0; j<i; j++){ count[i] += count[j]*count[i-j-1]; } } return count ; }
相关文章推荐
- iOS实现UIImageView透明区域点击事件穿透
- [ios]自定义UI
- UITableView主要知识框架
- Fuel 7.0介绍
- #import <Cocoa/Cocoa.h> 报错 Lexical or Preprocessor Issue 'Cocoa/Cocoa.h' file not found
- ios中UIActivityIndicatorView使用
- MySql 启动报错:The server quit without updating PID file 如何解决
- Selenium IDE-自动化ui测试插件安装及使用
- php统计数组中各项的个数用函数array_count_values
- uva 11324 The Largest Clique(强连通分量 + DAG)
- systemtap gui
- Windows管理多个java版本--解决'has value '1.8',but'1.7' is required'的方法
- UISearchbar 常用代理方法
- 【转】使用segue页面间传递数据
- Java集合类: Set、List、Map、Queue使用场景梳理
- WPF:如何在工作线程中更新窗体的UI元素(Dispatcher机制)
- 解决PKIX path building failed的问题
- Request获取url信息的各种方法比较 及 Request.UrlReferrer详解
- zoj3892Available Computation Sequence(区间dp)
- UGUI的image的属性