繁体   English   中英

就 n 和 m 而言,以下算法的运行时复杂度是多少?

[英]What is the run-time complexity of the following algorithm, in terms of n and m?

def print_all_codes(n, m):

    def print_01_codes(current, num_digits):
        if num_digits == 0:
            print(current)
        else:
            print_01_codes('0' + current, num_digits - 1)
            print_01_codes('1' + current, num_digits - 1)

    upper_bound = 0

    while True:
        for i in range(upper_bound):
            print_01_codes('', n)

        if upper_bound > m:
            break

        upper_bound += 1

我已经尝试解决这个问题一段时间了,我得出的唯一结论是:O(m*2^n) 我见过另一个问题的措辞相似,但对该问题的结论尚无定论。 类似问题

while 循环本质上是 1+2+...+M 次和 O(M^2)。 print_01_codes 打印 n 位的所有二项式可能性,因此它必须是 O(2^N)。 正如 John 在评论中指出的那样,concat/print 函数与 N 成比例。

加起来就是 O((M^2) N (2^N))

不幸的是,答案是相当讨厌的。 首先,我们必须讨论print_01_codes算法的复杂性。

num_digits = 0的基本情况下,算法将执行ϴ(length(current))因为我们正在打印长度为current的字符串。 当我们处于递归情况时,我们将总共达到基本情况2^num_digits次,基本情况字符串的长度为length(current) + num_digits 这为我们提供了Ω((num_digits + length(current)) 2^num_digits)时间的下限。 事实证明,这也是时间的上限,因为在递归树的每个节点都完成了O(length(current + num_digits))工作,因此print_01_codes算法采用ϴ((num_digits + length(current)) 2^num_digits)时间。

分析循环,我们看到我们将调用print_01_codes('', n)总共ϴ(m^2)次。 这将给我们总共ϴ(nm^2 2^n)时间。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM