繁体   English   中英

就 n 和 m 而言,运行时复杂度是多少?

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

这是一个编码面试问题。 就 n 和 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
 while True:

        for i in range(upper_bound):

            print_01_codes('', n)

        if upper_bound > m:

            break

        upper_bound += 1

此循环与此循环相同:

for i in range(m):
    for j in range(i):
       #Function

这个循环时间复杂度是这样的: 1 + 2 + 3 + 4 +... + m-1 => (m-1)*(m) / 2 => O(m^2)关于你的#Function:


        if num_digits == 0:

            print(current)

        else:

            print_01_codes('0' + current, num_digits - 1)

            print_01_codes('1' + current, num_digits - 1)

这是一个递归的 function,这就像一棵完整的二叉树。 所以它是O(2^n) 您的代码时间复杂度为O(m^2 * 2^n)

暂无
暂无

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

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