问题
I have an algorithm i'm trying to implement. I've been asked to determine a function that describes its worst case running time. As input, it takes an array of some length (lets call it n). Then what it does is as follows:
if (n==0){ return 0;}
else if(n==1){return A[0];}
else{
return f(n-1)+f(n-2)
}
Sorry if I'm a tad sparse on the implementation details, but in a sense, its rather similar to something like the fibbanoci sequence. I'm thinking the worst case running time of this algorithm is t(n)=2^n, because if n is large, it will decompose into 2 separate calculations, which in turn will split into 2 more and so on. I'm just not sure how to formally justify this
回答1:
Let's first get a recursion for the running time.
T(0) = T(1) = 1
since both just return a number (one is an array-lookup, but that's constant time too). And for n > 1
we have
T(n) = T(n-1) + T(n-2) + 1
since you evaluate f(n-1)
and f(n-2)
and add the two results. That's almost the same recurrence as the Fibonacci sequence itself, F(n) = F(n-1) + F(n-2)
, and the result is closely related.
n | T(n) | F(n)
----------------
0 | 1 | 0
1 | 1 | 1
2 | 3 | 1
3 | 5 | 2
4 | 9 | 3
5 | 15 | 5
6 | 25 | 8
7 | 41 | 13
8 | 67 | 21
9 | 109 | 34
10 | 177 | 55
11 | 287 | 89
If you look at the values, you see that
T(n) = F(n+2) + F(n-1) - 1
and can prove that with induction, if you need to.
Since the terms of the Fibonacci sequence are given by F(n) = (φ^n - (1-φ)^n)/√5
, where φ = (1 + √5)/2
, you see that the complexity of your f
is also Θ(φ^n)
, like that of the Fibonacci sequence. That's better than Θ(2^n)
, but still exponential, so calculation using this way is only feasible for small n
.
来源:https://stackoverflow.com/questions/12655496/worst-case-running-time-of-this-algorithm-how-to-justify