[leetcode] 96. Unique Binary Search Trees
来源:互联网 发布:kali linux安装输入法 编辑:程序博客网 时间:2024/05/29 18:10
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
catalan number,然后用dp去做。分析一下:dp[0] = 1, dp[1] = 1, dp[n]的个数是左右subtree种数的乘积
dp[2]= dp[0]*dp[1] (root为1)
+ dp[1]*dp[0] (root为2)
dp[3] = dp[0]*dp[2](root为1)
+ dp[1]*dp[1] (root为2)
+ dp[2]*dp[0] (root为3)
所以公式就是 dp[n] = sum_(0:n-1) dp[i]*dp[n-i-1]
class Solution {public: int numTrees(int n) { vector<int> dp(n+1); 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.back(); }};
0 0
- LeetCode 96. Unique Binary Search Trees II
- [LeetCode]96.Unique Binary Search Trees
- 96. Unique Binary Search Trees Leetcode
- [Leetcode] 96. Unique Binary Search Trees
- LeetCode --- 96. Unique Binary Search Trees
- [leetcode] 96.Unique Binary Search Trees
- [leetcode] 96. Unique Binary Search Trees
- 96. Unique Binary Search Trees LeetCode
- <LeetCode OJ> 96. Unique Binary Search Trees
- [LeetCode]96. Unique Binary Search Trees
- [LeetCode]96. Unique Binary Search Trees
- LeetCode 96. Unique Binary Search Trees
- *LeetCode 96. Unique Binary Search Trees
- Leetcode 96. Unique Binary Search Trees
- LeetCode *** 96. Unique Binary Search Trees
- LeetCode 96. Unique Binary Search Trees
- LeetCode 96.Unique Binary Search Trees
- Leetcode:96. Unique Binary Search Trees
- 为什么基于比较的排序算法,时间复杂度总是大于等于nlgn
- 正向代理与反向代理的区别
- iOS图像处理(5)填充模式
- hdu 4283 You Are the One(区间DP)
- 在CentOS系统上格式化逻辑分区的方法
- [leetcode] 96. Unique Binary Search Trees
- Codeforces Round #367 (Div. 2)-Vasiliy's Multiset-最大异或和-trie
- Codeforces Round #367 (Div. 2)-C - Hard problem-DP
- c语言栈实现括号匹配
- js 性能优化总结
- [leetcode] 382. Linked List Random Node 解题报告
- [leetcode] 309. Best Time to Buy and Sell Stock with Cooldown
- OI算法的时空复杂度及算法模板
- Linux写时拷贝技术(copy-on-write)