递归算法的运行时

Runtime for recursive algorithm

上面的算法,我只能算出

的运行时间
if n==0:

为 1,

的运行时间
rec_opt(n-1)

将是 T(n-1)。 但是我无法弄清楚

的运行时间
rec_opt(p[n])

以及为什么递归具有指数封闭形式,O(2^n )

此外,为什么这个算法会是O(n)。

rec_opt(p[n])

对于递归调用rec_opt(p[n]),将有另一个递归树,其作用类似于rec_opt(n-1)。由于 p[n] 可以是 1 - n 中的任何值,因此我们可以假设它的行为类似于 rec_opt(n).

And furthermore, why this algorithm will be O(n).

在算法的第二部分做memoization,它不会一次又一次地计算相同的子问题。这就是复杂性大幅降低到 O(n) 的原因。

更多请查看dynamic programming.