【问题标题】:What will be the complexity of this code for counting number of different BST(binary search tree)s from N nodes?从 N 个节点计算不同 BST(二叉搜索树)数量的代码的复杂性是多少?
【发布时间】:2013-09-29 15:49:30
【问题描述】:
def count(n):
    if n == 0 or n == 1:
        return 1
    else:
        sum = 0 
        left = 0        
        right = 0
        for x in range(1,n+1):
            left = count(x-1)
            right = count(n-x)
            sum +=  left * right
    return sum

我正在阅读这篇文章,我想知道 如果 n 个节点中没有不同的二叉搜索树是

(2n)! / ((n+1)! * n!) 来自 this 帖子。

然后

  1. 时间复杂度是多少?在!) ?
  2. 什么是递归关系?

【问题讨论】:

    标签: python algorithm binary-tree complexity-theory time-complexity


    【解决方案1】:

    当您调用count(n) 时,它会调用count(0)count(n-1) 中的每一个两次

    所以我认为你可以这样写循环:

    T(n) = 2 * sum[T(0) upto T(n-1)] + nk 其中k代表乘法和求和部分。

    现在考虑:

    T(n+1) = 2 * sum[T(0) upto T(n)] + (n+1)k
           = 2 * sum[T(0) upto T(n-1)] + 2T(n) + nk + k
           = T(n) + 2T(n) + k
           = 3T(n) + O(1)
    

    解决这个问题,它似乎具有O(3^n) 的复杂性。

    【讨论】:

    • 如果你指的是加泰罗尼亚数字的增长,那没有任何意义。函数本身的增长和计算值的方式是两个不同的问题。
    猜你喜欢
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 2015-05-14
    • 2013-02-25
    • 2020-03-23
    • 2015-02-21
    • 2014-03-22
    相关资源
    最近更新 更多