码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode96. Unique Binary Search Trees

时间:2018-06-03 14:27:36      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:hat   ural   any   通过   man   count   tput   mtr   取值   

题目:

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

标签:hat   ural   any   通过   man   count   tput   mtr   取值   

原文地址:https://www.cnblogs.com/plank/p/9128660.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!