[英]Create an algorithm whose recurrence is T(n) = T(n/3) + T(n/4) + O(n^2)
我如何 go 关于这样的问题: T(n) = T(n/3) + T(n/4) + O(n^2)
我可以使用两个 for 循环,这会给我O(n^2)
,对吧?
为了解释这个等式,用英文读为:“大小为 n 的输入的运行时间等于大小为 n/3 的输入的运行时间,加上大小为 n/4 的输入的运行时间,再加上时间与 n^2" 成正比。
例如,使用嵌套循环可以编写与 n^2 成比例运行的代码,尽管编写像for i in range(n ** 2): ...
这样的单个循环更简单。
编写运行时间等于输入大小为 n/3 或 n/4 的算法所需时间的代码甚至更容易 - 只需使用该大小的输入递归调用算法。 (不要忘记递归终止的基本情况。)
放在一起,代码可能看起来像这样:
def nonsense_algorithm(n):
if n <= 0:
print('base case')
else:
nonsense_algorithm(n // 3)
nonsense_algorithm(n // 4)
for i in range(n ** 2):
print('constant amount of text')
我使用了 integer 除法(向下舍入),因为我认为否则没有意义。
在这里,我们将使用for
和range(start, stop, steps)
,可能使用简单易懂的算法,类似于:
def algorithm_n2(n: int) -> int:
"""Returns an integer for a O(N2) addition algorithm
:n: must be a positive integer
"""
if n < 1:
return False
output = 0
for i in range(n):
for j in range(n):
output += n * 2
for i in range(0, n, 3):
output += n / 3
for i in range(0, n, 4):
output += n / 4
return int(output)
# Test
if __name__ == "__main__":
print(algorithm_n2(24))
在方法中使用
print()
并不是最佳实践。
27748
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.