【LEETCODE】96-Unique Binary Search Trees
2015-11-03 22:07
591 查看
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
参考:
用卡特兰数解决:南郭子綦:leetcode实现代码
http://www.cnblogs.com/zuoyuan/p/3747824.html 卡特兰数解决思路:n个节点构成的二叉树,共有多少种情形?
http://buptdtt.blog.51cto.com/2369962/832586 更详细解释 http://blog.csdn.net/vidio/article/details/6787899 扩展:从《编程之美》买票找零问题说起,娓娓道来卡特兰数——兼爬坑指南
http://www.cnblogs.com/wuyuegb2312/p/3016878.html
思路:
给 n 个节点,设要求的个数为 f(n)
则 n=0时,f(n)=1,n=1时,f(n)=1
当 n>2时,留 1个节点作为 root,那么剩下 n-1个节点,在左右子树的分配方式具有如下情形:
左 右
0 n-1
1 n-2
...
n-1 0
此时,组合的数为 f(n)=f(0)*f(n-1)+f(1)*f(n-2)+...+f(n-1)*f(0)
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
参考:
用卡特兰数解决:南郭子綦:leetcode实现代码
http://www.cnblogs.com/zuoyuan/p/3747824.html 卡特兰数解决思路:n个节点构成的二叉树,共有多少种情形?
http://buptdtt.blog.51cto.com/2369962/832586 更详细解释 http://blog.csdn.net/vidio/article/details/6787899 扩展:从《编程之美》买票找零问题说起,娓娓道来卡特兰数——兼爬坑指南
http://www.cnblogs.com/wuyuegb2312/p/3016878.html
思路:
给 n 个节点,设要求的个数为 f(n)
则 n=0时,f(n)=1,n=1时,f(n)=1
当 n>2时,留 1个节点作为 root,那么剩下 n-1个节点,在左右子树的分配方式具有如下情形:
左 右
0 n-1
1 n-2
...
n-1 0
此时,组合的数为 f(n)=f(0)*f(n-1)+f(1)*f(n-2)+...+f(n-1)*f(0)
class Solution(object): def numTrees(self, n): """ :type n: int :rtype: int """ dp=[1,1] if n<=1: #因range(n-1) n-1>=1 return dp else: dp += [0 for i in range(n-1)] #为dp[i]赋初始值0 for i in range(2,n+1): #i=2,3,...n for j in range(0,i): #j=0,...n-1 dp[i]+=dp[j]*dp[i-1-j] #dp =0+dp[0]*dp[n-1]+...+dp[n-1]*dp[0] return dp
相关文章推荐
- hdu1159 Common Subsequence(LCS)
- 【Android】安卓UI 进度对话框ProgressDialog
- iOS—UI —懒加载
- CloudSuite之Graph Analytics集群安装
- iOS 开发之UIDynamic
- [TwistedFate]NSArray NSNumber NSValue
- why not the search engine build index for special character
- UIScrollView
- UITableView中动态返回自定义cell的高度
- hdu1503 Advanced Fruits (简单LCS)
- Codeforces Round #327 590B Chip 'n Dale Rescue Rangers(等效转换,二分)
- LeetCode 115: Distinct Subsequences
- mongo客户端mongo VUE增删改查
- 【Android】安卓UI button选择器
- [POJ 2524]Ubiquitous Religions 并查集
- [300]Longest Increasing Subsequence
- Dwz(J-UI)框架--入门
- UIView convertRect
- Android_uiautomator支持输入中文
- getRequestDispatcher()与sendRedirect()的区别