加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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


思路:
这个问题可以被拆分,若选取值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]

顺利通过~

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读