LeetCode96. Unique Binary Search Trees
发布时间:2020-12-14 04:48:49 所属栏目:大数据 来源:网络整理
导读:题目: Given? n ,how many structurally unique?BST‘s?(binary search trees) that store values 1 ...? n ? Example: Input: 3Output: 5Explanation: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
题目: 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 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] 顺利通过~ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |