LeetCode96. Unique Binary Search Trees
Posted 板弓子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode96. Unique Binary Search Trees相关的知识,希望对你有一定的参考价值。
题目:
Given n, how many structurally unique BST‘s (binary search trees) that store values 1 ... n?
Example:
Input: 3 Output: 5 Explanation: 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
思路:
这个问题可以被拆分,若选取值i为根节点,则1,2,...,i - 1为左子树上的点,i + 1, i + 2, ..., n为右子树上的点(由搜索二叉树的性质可得)。而取i为根节点的组合数应为左子树的种类数*右子树的种类数。由此可以拆分,得到下边这种直接迭代的代码:
1 class Solution(object): 2 def numTrees(self, n): 3 """ 4 :type n: int 5 :rtype: int 6 """ 7 if n < 1: 8 return 0 9 return self.count_tree(1, n) 10 11 def count_tree(self, left, right): 12 if left >= right: 13 return 1 14 res = 0 15 for i in range(left, right + 1): 16 res += self.count_tree(left, i - 1) * self.count_tree(i + 1, right) 17 return res
提交后显示运行时间超时。原来是代码中有太多重复迭代,如同求解斐波那契数列时的直接迭代解法。因此使用从底向上的解法:
class Solution(object): def numTrees(self, n): """ :type n: int :rtype: int """ if n < 1: return 0 trees = [0 for _ in range(n + 1)] trees[0], trees[1] = 1, 1 for i in range(2, n + 1): for j in range(1, i + 1): trees[i] += trees[j - 1] * trees[i - j] return trees[n]
顺利通过~
以上是关于LeetCode96. Unique Binary Search Trees的主要内容,如果未能解决你的问题,请参考以下文章
Java [Leetcode 96]Unique Binary Search Trees
[动态规划] leetcode 96 Unique Binary Search Trees
Leetcode 96. Unique Binary Search Trees
Leetcode 96. Unique Binary Search Trees