【LEETCODE】96-Unique Binary Search Trees
来源:互联网 发布:淘宝买家退货率高后果 编辑:程序博客网 时间:2024/06/05 23:20
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)
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[n] 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[n]=0+dp[0]*dp[n-1]+...+dp[n-1]*dp[0] return dp[n]
- LeetCode 96 Unique Binary Search Trees II
- [leetcode 96] Unique Binary Search Trees
- Leetcode NO.96 Unique Binary Search Trees
- leetcode || 96、Unique Binary Search Trees
- [Leetcode 96, Medium] Unique Binary Search Trees
- leetcode-96 Unique Binary Search Trees
- Unique Binary Search Trees - LeetCode 96
- 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(c++)
- leetcode 96: Unique Binary Search Trees
- leetCode #96 Unique Binary Search Trees
- leetcode 95-96:Unique Binary Search Trees
- 字符串压缩
- 深入理解iOS API系列(四)理解CNContactPickerDelegate
- net.sf.hibernate.PropertyNotFoundExceptio
- 【二叉树】关于二叉树的后续遍历遍历以及栈
- C语言/函数指针
- 【LEETCODE】96-Unique Binary Search Trees
- sql cookbook 笔录(一)
- Android中的OptionsMenu,ContextMenu,pupMenu例子
- 求i<j<p<q w[i]×w[p]=w[j]×w[q]总数 STL map SRM 671 div1 500: BearDarts
- POJ 3746 Teacher YYF (打表)
- UIImageView不能设置圆角的解决方法
- Add Binary
- 在Maven中新增自定的jar包
- 解决confluence的乱码问题