leetcode: 96. Unique Binary Search Trees
来源:互联网 发布:json 中括号 编辑:程序博客网 时间:2024/06/14 10:17
Q
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
AC
class Solution(object): def numTrees(self, n): """ :type n: int :rtype: int """ if n==0:return 1 if n==1:return 1 if n==2:return 2 if n==3:return 5 self.map = {0:1, 1:1, 2:2, 3:5} return self._getnum(n) def _getnum(self, n): if n in self.map: return self.map[n] total = 0 for i in range(n): left = self._getnum(i) right = self._getnum(n-i-1) total += left*right self.map[n] = total return total# Time: O(n)# Space: O(1)# Math solution.class Solution2(object): def numTrees(self, n): """ :type n: int :rtype: int """ if n == 0: return 1 def combination(n, k): count = 1 for i in xrange(1, k + 1): count = count * (n - i + 1) / i; return count return combination(2 * n, n) - combination(2 * n, n - 1)# Time: O(n^2)# Space: O(n)# DP solution.class Solution3(object): def numTrees(self, n): counts = [1, 1] for i in xrange(2, n + 1): count = 0 for j in xrange(i): count += counts[j] * counts[i - j - 1] counts.append(count) return counts[-1]if __name__ == "__main__": assert Solution().numTrees(3) == 5
阅读全文
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
- 分布式事务
- Android调用系统相机、图库、裁剪图片并压缩上传(适配7.0)
- Hyperledger Fabric SDK 示例fabric-samples-《balance-transfer》之十二《查询已经加入的channel名称》
- 平衡二叉树(AVL树)一图一步骤代码实现左旋右旋,左右平衡操作
- MVVM
- leetcode: 96. Unique Binary Search Trees
- Tether宣布3000万美元代币被盗
- Ubuntu install sogoupinyin
- 编程规范 命名风格 摘自《阿里巴巴 Java 开发手册》
- Java之HashMap简答题——2017.11.18
- JQuery相关的知识点
- C++的cout高阶格式化操作
- 学习AngularJs:Directive指令用法(完整版)
- Elasticsearch(处理冲突)