【问题标题】:Recurrence relation and time complexity of finding next larger in Generic tree在通用树中寻找下一个较大的递归关系和时间复杂度
【发布时间】:2020-12-11 05:05:15
【问题描述】:

问题:给定一棵通用树和一个整数 n。在树中查找并返回具有下一个较大元素的节点,即找到一个值刚好大于 n 的节点。

虽然我能够通过删除后面的 for 循环并在调用递归时进行比较来解决它是 O(n)。我有点好奇以下代码版本的时间复杂度。

我提出了递归关系为 T(n) = T(n-1) + (n-1) = O(n^2)。其中 T(n-1) 是孩子们花费的时间,+ (n-1) 是为了找到下一个更大的(第二个 for 循环)。我做对了吗?还是我错过了什么?

def nextLargestHelper(root, n):
"""
root => reference to root node
n => integer
Returns node and value of node which is just larger not first larger than n.
"""
# Special case
if root is None:
    return None, None
# list to store all values > n
largers = list()
# Induction step
if root.data > n:
    largers.append([root, root.data])
# Induction step and Base case; if no children do not call recursion
for child in root.children:
    # Induction hypothesis; my function returns me node and value just larger than 'n'
    node, value = nextLargestHelper(child, n)
    # If larger found in subtree
    if node:
        largers.append([node, value])
# Initialize node to none, and value as +infinity
node = None
value = sys.maxsize
# travers through all larger values and return the smallest value greater than n
for item in largers: # structure if item is [Node, value]
    # this is why value is initialized to +infinity; so as it is true for first time
    if item[1] < value:
        node = item[0]
        value = item[1]
return node, value

【问题讨论】:

    标签: python algorithm recurrence


    【解决方案1】:

    首先:请为 O-Notation 和 inputvalues 使用不同的字符。

    您只“触摸”每个节点一次,因此结果应该是O(n)。有点特别的是你的算法在之后找到最小值。您可以将其包含在您的全部儿童循环中,以便更轻松地进行复发估计。事实上,您也对列表的最小值进行了重复估计。

    您的递归方程应该看起来更像T(n) = a*T(n/a) + c = O(n),因为在每个步骤中,您都有a 子树形成a 子树,大小为(n-1)/a。在每个步骤中,除了一些常数因素之外,您还可以计算最多包含 a 元素的列表的最小值。您可以将其写为a*T(n/a) + a*c1 +c2,它与a*T(n/a) + c 相同。实际的公式看起来更像这样:T(n) = a*T((n-1)/a) + c 但n-1 使得应用主定理变得更加困难。

    【讨论】:

    • 出色而直观的分析。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-17
    • 1970-01-01
    • 2019-07-28
    相关资源
    最近更新 更多