96. Unique Binary Search Trees
来源:互联网 发布:瑞士莲 费列罗 知乎 编辑:程序博客网 时间:2024/05/22 21:02
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n.
For example,
Given n = 3, your program should return all 5 unique BST's shown below.
1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
The idea is Suppose we know the solution from 1 to n-1, and we want to know about n;
F(n) = 0;
We could choose a number X from 1 to n to be the root, and all the numbers in the left subtree i < X and in the right tree i > X
There are (i - 1) number in the left tree and (n - i) number in the right tree.
F(n) += F(i - 1) * F(n - i) for i from 1 to N
Code:
public class Solution { public int numTrees(int n) { int[] dp = new int[n + 1]; dp[1] = 1; dp[0] = 1; if(n <= 1) return 1; for(int i = 2; i <= n; i++){ for(int k = 0; k < i; k++){ dp[i] += dp[k]*dp[i-k-1]; } } return dp[n]; }}
in the above code k stands for how many number in the left tree and (i - k - 1) stands for how many number in the right tree.
0 0
- 96.Unique Binary Search Trees
- 96. Unique Binary Search Trees
- 96. Unique Binary Search Trees
- 96. Unique Binary Search Trees
- 96. Unique Binary Search Trees
- 96. Unique Binary Search Trees
- 96. Unique Binary Search Trees
- 96. Unique Binary Search Trees
- 96. Unique Binary Search Trees
- 96. Unique Binary Search Trees
- 96. Unique Binary Search Trees
- 96. Unique Binary Search Trees
- 96. Unique Binary Search Trees
- 96. Unique Binary Search Trees
- 96. Unique Binary Search Trees
- 96. Unique Binary Search Trees
- 96. Unique Binary Search Trees
- 96. Unique Binary Search Trees
- Spark知识体系完整解读
- 使用Jetbrains的Gogland IDE阅读Consul源码
- 多字节转UTF-8
- 用Tomcat服务器配置https双向认证过程实战
- 面向对象程序设计 授课计划
- 96. Unique Binary Search Trees
- 复现 OOM
- leetcode
- 机器学习评价指标大汇总
- 存储过程,视图,游标,流程控制语句,异常处理
- 大数据分析在金融行业的应用与趋势
- 3.1 我的unreal4征程之旅开始--关于VS中直接启动游戏
- mysqli 过程
- MapReduce工作原理图文详解