【问题标题】:What is the complexity of the given function [duplicate]给定函数的复杂度是多少[重复]
【发布时间】:2021-10-01 10:59:00
【问题描述】:

有人能告诉我函数的复杂性是什么吗?为什么? 谢谢

def func1(n):
    if n==0:
        return (1)
    if n==1:
        return (1)
    if n==2:
        return (2)
    return (n*func1(n-3))

n=int(input())
func1(n)

我认为复杂度是:“O(nlog n)”

【问题讨论】:

  • 对于所有肯定的ns,循环最多会有n / 3 迭代(你有一个尾递归)。然而,这仍然是线性时间 - O(n)。
  • @JanezKuhar,这是不是尾递归(但接近)。最后一个操作不是调用func1(),而是乘以n
  • 你通常会写return 1,而不是return (1)

标签: python function recursion time-complexity complexity-theory


【解决方案1】:

函数的时间复杂度为 O(n),因为 n - 3 是线性的。如果是除法运算,则为 O(logn)。进一步解释可以参考this

附:与 n 相乘本身不会影响每个递归调用中的给定参数,因此它根本不会影响时间复杂度。

【讨论】:

    猜你喜欢
    • 2011-11-11
    • 2013-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    相关资源
    最近更新 更多