5.3.1 Unique Binary Sear Trees
Notes: | |
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: dp. | |
*/ |
解题思路:
n=0,f(0)=0;
n=1,f(1)=1;
n=2,f(2)=f(0)*f(1)+f(1)*f(0)=2;
n=3,f(3)=f(0)*f(2)+f(1)*f(1)+f(2)*f(0)=5;
所以
class Solution {
public:int numTrees(int n) {return numTrees_2(n);}int numTrees_1(int n) {int dp[n+1];memset(dp, 0, sizeof(dp));dp[0] = 1;for (int i = 1; i <= n; ++i)for (int j = 0; j < i; j++)dp[i] += dp[j] * dp[i-j-1];return dp[n];}int numTrees_2(int n) {if (n < 0) return 0;vector<int> dp(n+1, 0);dp[0] = 1; dp[1] = 1;for(int i = 2;i <= n; ++i){dp[i] = dp[i-1] * (4 * i - 2)/(i + 1);}return dp[n]; }
};
5.3.1 Unique Binary Sear Trees相关推荐
- leetcode 95. Unique Binary Search Trees II | 96. Unique Binary Search Trees
95. Unique Binary Search Trees II https://leetcode.com/problems/unique-binary-search-trees-ii/ 题解 题是 ...
- 96. Unique Binary Search Trees(I 和 II)
Given n, how many structurally unique BST's (binary search trees) that store values 1-n? For example ...
- LeetCode 96. Unique Binary Search Trees
96. Unique Binary Search Trees Given n, how many structurally unique BST's (binary search trees) tha ...
- Unique Binary Search Trees ll -深度优先遍历DFS
题目:Unique Binary Search Trees ll English: Given an integer n, generate all structurally unique BST's ...
- 【重点 递归构造二叉树】LeetCode 95. Unique Binary Search Trees II
LeetCode 95. Unique Binary Search Trees II 本博客转载自:[1]https://segmentfault.com/a/1190000007443961 [2] ...
- 【卡塔兰数】LeetCode 96. Unique Binary Search Trees
LeetCode 96. Unique Binary Search Trees 本博客转载自:http://www.cnblogs.com/grandyang/p/4299608.html Solut ...
- Unique Binary Search Trees II -- LeetCode
原题链接: http://oj.leetcode.com/problems/unique-binary-search-trees-ii/ 这道题是求解所有可行的二叉查找树,从 Unique Bi ...
- [LeetCode]: 96: Unique Binary Search Trees
题目: Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For e ...
- 【Unique Binary Search Trees II】cpp
题目: Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. F ...
最新文章
- m.pythontab.com_python字符串连接的三种方法及其效率、适用场景详解
- python 读写utf8文件_Python关于 文件读写的总结
- java 管道设计_使用管道流实现Java 8阶段构建器
- css规则可以放在云上,CSS中!important规则的使用方法
- fritzing导入元件_超屌的 fritzing 新建元件
- 小程序分享如何自定义封面?
- 随想录(exe和dll的相互调用)
- ArcGIS案例学习笔记4_2_水文分析批处理地理建模
- 51单片机控制步进电机正反转
- 龙帝国与避风港最新网址
- 面向接口编程思想(的好处)
- 淘宝用户行为分析项目报告
- 怎样学好高中数学学好高中数学的技巧
- 如何快速去除图片上的水印
- 关于Floyd算法 和 Dijkstra算法
- 服务器文件备份到本地方法,Windows服务器文件备份到本地的方法、Windows服务器数据备份方案...
- Hudi Clean 清理文件实现分析
- Md5工具包加密之MD5Util
- 循环-求一个数各位数字的和
- linux java excel文件_使用Java语言将excel中读取到的内容导入Linux的文件中