首页 > 其他 > 详细

[Lintcode]163. Unique Binary Search Trees

时间:2019-02-10 18:29:42      阅读:167      评论:0      收藏:0      [点我收藏+]

163. Unique Binary Search Trees

  • 本题难度: Medium
  • Topic: Bit Manipulation

Description

Given n, how many structurally unique BSTs (binary search trees) that store values 1...n?

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

我的代码

class Solution:
    """
    @param n: An integer
    @return: An integer
    """
    def numTrees(self, n):
        # write your code here
        
        A = [1, 1, 2]
        if n<3:
            return A[n]
        for i in range(3,n + 1):
            res = 0
            for j in range(i):
                res += A[j]*A[i - j - 1]
            A.append(res)
        return A[-1]
        

思路

假设f(x)为x个结点的不同的二叉搜索树数目。
n个结点的二叉搜索树,可以选取其中任何一个数k为根结点。
则左子树由1~k-1构成,右子树由k+1~n构成。则左子树一共有f(k-1)种情况,右子树有f(n-k-2)种情况。

  • 时间复杂度 O(log(n))

[Lintcode]163. Unique Binary Search Trees

原文:https://www.cnblogs.com/siriusli/p/10359899.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!