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

[Lintcode]163. Unique Binary Search Trees

发布时间:2020-12-14 04:25:17 所属栏目:大数据 来源:网络整理
导读: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

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))

(编辑:李大同)

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

    推荐文章
      热点阅读