LeetCode Unique Binary Search Trees
来源:互联网 发布:小程序cms系统 编辑:程序博客网 时间:2024/06/15 17:55
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
看到题目,第一个想法就是将所有BST列出来然后进行统计,这个方法很直接。但想了半天也没有给出什么好的实现代码,后来看别人的解法,提到了动态规划,发现还是动态规划大法好。
动态规划的核心就是动态规划方程,这道题如何建模动态规划方程?假设以1为根节点,那么根据BST的性质可以知道,其左子树没有节点,右子树有n-1个节点,以此类推出其它情况,获取动态规划方程如下:
以1为根,F(1) = F(0)*F(n-1)
以2为根,F(2) = F(1)*F(n-2)
....
以n为根,F(n) = F(n-1)*F(0)
代码如下:
class Solution {public: int numTrees(int n) { int dp[n+1]; dp[0] = dp[1] =1; for(int i=2;i<=n;i++) { dp[i] = 0; for(int j=0;j<i;j++) { dp[i] += dp[j]*dp[i-1-j]; } } return dp[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
- Maven 编译错误 Dynamic Web Module 3.0 requires Java 1.6 or newer 解决方案
- 基础算法(三)---二分排序(Java)
- Redis Replication
- 初次尝试使用http-server
- 使用UGUI制作虚拟摇杆
- LeetCode Unique Binary Search Trees
- 泛型理解
- ReactJs学习(环境配置,一个hello world)
- 一位5年的高手总结文
- 网络状态的判断
- Kotlin学习记录(五)—— 条件表达式的使用
- Cygwin安装教程
- Could not find bundle: org.eclipse.equinox.console
- VSCode使用