[LeetCode]Unique Binary Search Trees
来源:互联网 发布:sas 优化案例 编辑:程序博客网 时间:2024/06/13 23:29
Question
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
本题难度Medium。
DP
【复杂度】
时间 O(N) 空间 O(N)
【思路】
可以参照(复习)[LeetCode]Unique Binary Search Trees II,设n的BST的个数为f(1,n)
,则可以看到:
实际上,
因此可以进一步地化简,我们用
f(n)
表示BST的个数,则:然后我们利用DP对
f(0)
到f(n)
的值依次进行计算即可。【代码】
public class Solution { public int numTrees(int n) { //require int[] f=new int[n+1]; if(n<1) f=new int[2]; f[0]=1;f[1]=1; //invariant for(int k=2;k<=n;k++) for(int i=1;i<=k;i++) f[k]+=f[i-1]*f[k-i]; //ensure return f[n]; }}
0 0
- LeetCode: Unique Binary Search Trees
- LeetCode : Unique Binary Search Trees
- [Leetcode] Unique Binary Search Trees
- [LeetCode]Unique Binary Search Trees
- LeetCode Unique Binary Search Trees
- Leetcode: Unique Binary Search Trees
- LeetCode-Unique Binary Search Trees
- [leetcode] Unique Binary Search Trees
- LeetCode - Unique Binary Search Trees
- [LeetCode] Unique Binary Search Trees
- 【Leetcode】Unique Binary Search Trees
- Leetcode: Unique Binary Search Trees
- 【LeetCode】Unique Binary Search Trees
- Leetcode Unique Binary Search Trees
- Leetcode: Unique Binary Search Trees
- [LeetCode] Unique Binary Search Trees
- Leetcode: Unique Binary Search Trees
- LeetCode | Unique Binary Search Trees
- MySQL表复制,数据复制解析
- Vojnici
- Dubbo中使用高效的Java序列化(Kryo和FST)
- Log4j.properties 属性详解
- MapReduce开发的基础知识
- [LeetCode]Unique Binary Search Trees
- 【POJ 2891 Strange Way to Express Integers】+ 扩展欧几里德
- JHipster入门
- 串行通讯之.NET SerialPort
- haproxy+keepalived+mycat+mysql (读写分离)
- 排序用法 order by asc desc
- 关于Python pip 安装第三方模块失败
- 《C++ Primer》读书笔记-第五章 语句
- 相机的Angle of View, Field of view && Focal length