96. Unique Binary Search Trees
2016-07-16 11:25
393 查看
题目:
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.
题意:
给定整数n,问一共有多少种结构唯一的二叉搜索树存储1到n。
![](http://img.blog.csdn.net/20160716112811531?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
![](http://img.blog.csdn.net/20160716112742924?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
思路一:
动态规划解。此题是 Catalan Number卡塔兰数的一个例子。
Catalan Number卡塔兰数定义:是组合数学中一个常出现在各种计数问题中出现的数列,以比利时的数学家欧仁·查理·卡塔兰 (1814–1894)的名字来命名,其前几项为 : 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845, 35357670, 129644790, 477638700, 1767263190, 6564120420, 24466267020, 91482563640,
343059613650, 1289904147324, 4861946401452, ...
令h(0)=1,h(1)=1,catalan数满足递推式[1] :
h(n)= h(0)*h(n-1)+h(1)*h(n-2) + ... + h(n-1)h(0) (n>=2)
例如:h(2)=h(0)*h(1)+h(1)*h(0)=1*1+1*1=2
h(3)=h(0)*h(2)+h(1)*h(1)+h(2)*h(0)=1*2+1*1+2*1=5
另类递推式[2] :
h(n)=h(n-1)*(4*n-2)/(n+1);
递推关系的解为:
h(n)=C(2n,n)/(n+1) (n=0,1,2,...)
递推关系的另类解为:
h(n)=c(2n,n)-c(2n,n-1)(n=0,1,2,...)
代码:C++版:0ms
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
题意:
给定整数n,问一共有多少种结构唯一的二叉搜索树存储1到n。
思路一:
动态规划解。此题是 Catalan Number卡塔兰数的一个例子。
Catalan Number卡塔兰数定义:是组合数学中一个常出现在各种计数问题中出现的数列,以比利时的数学家欧仁·查理·卡塔兰 (1814–1894)的名字来命名,其前几项为 : 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845, 35357670, 129644790, 477638700, 1767263190, 6564120420, 24466267020, 91482563640,
343059613650, 1289904147324, 4861946401452, ...
令h(0)=1,h(1)=1,catalan数满足递推式[1] :
h(n)= h(0)*h(n-1)+h(1)*h(n-2) + ... + h(n-1)h(0) (n>=2)
例如:h(2)=h(0)*h(1)+h(1)*h(0)=1*1+1*1=2
h(3)=h(0)*h(2)+h(1)*h(1)+h(2)*h(0)=1*2+1*1+2*1=5
另类递推式[2] :
h(n)=h(n-1)*(4*n-2)/(n+1);
递推关系的解为:
h(n)=C(2n,n)/(n+1) (n=0,1,2,...)
递推关系的另类解为:
h(n)=c(2n,n)-c(2n,n-1)(n=0,1,2,...)
代码:C++版:0ms
class Solution { public: int numTrees(int n) { vector<int> f(n+1, 0); f[0] = 1; f[1] = 1; for (int i=2; i<=n; ++i) { for (int k=1; k<=i; ++k) { f[i] += f[k-1] * f[i-k]; } } return f ; } };
相关文章推荐
- APUE读书笔记-第五章 标准I/O库
- [hdu 1711] Number Sequence [kmp]
- request对象
- xilium CefGlue集成包
- POJ-2031 Building a Space Station
- jsp页面通过request传值
- 搜索框使用,UISearchBarDelegate
- easyUI中文乱码
- 96. Unique Binary Search Trees
- 我所了解的MessageQueue的消息存放过程
- 滑动视图的循环滑动
- UVA-10420 List of Conquests
- iOS开发从入门到精通--UIWindow基础
- 357. Count Numbers with Unique Digits
- java序列号 SerializeUID
- aapt.exe finished with nonzero exit value 1
- 关于面试中的一二 ------------UI控件 持续更新
- AbstractQueue抽象类源码解析
- Deque接口源码解析
- 解决“Dynamic Web Module 3.0 requires Java 1.6 or newer.”错误