问题
Suppose I have a recursive algorithm that splits input into 2 inputs of size n-1 and solves them recursively. It combines the results in a constant time say c.
So formulating an equation for this,
T(n) = 2T(n-1) + c
In order to find the complexity of this one, I used the recursive tree method. Since input is divided into 2 at each step, the number of nodes will get squared at each step while since only one element is getting eliminated, every level will lose only one element from the list.
So I think that the complexity of this problem should be Θ(n2)
Am I right in this thought process. If not, What am I doing wrong?
Thank you.
回答1:
The number of nodes at each step doesn't get squared. Instead, it doubles at every level. For example, the number of nodes at
- problem size n: 1
- problem size n - 1: 2
- problem size n - 2: 4
- problem size n - 3: 8
- problem size n - 4: 16
- ...
- problem size n - i: 2i
As a result, the total number of nodes in your recursion tree will be 1 + 2 + 4 + 8 + ... + 2n = 2n+1 - 1. Accordingly, the work done will be c2n+1 - c, which is Θ(2n). This is exponential time, rather than quadratic time.
Hope this helps!
回答2:
The complexity is actually exponential: Omega(2^n).
Let's prove it using mathematical induction. For simplicity - assume c=1
Claim: T(n) >= 2^n
Base: T(0) = 1 (Let's take it as assumption)
Assume the claim is true for each k<n and using it let's prove:
T(n) = 2*T(n-1) + 1 >= 2*2^(n-1) + 1 = 2^n + 1 > 2^n
Now, to wrap it up let's show it is also O(2^n) and we will conclude this is Theta(2^n):
Claim: T(n) <= 2*2^n - 1
Base: T(0) = 1 = 2 -1
Assume the claim is true for each k<n and using it let's prove:
T(n) = 2*T(n-1) + 1 <= 2 * (2*2^(n-1) -1 ) + 1 = 2*2^n -2 + 1 = 2*2^n -1
As you can see, we actually get exactly 2*2^n-1 (The <= can be easily replaced with = in the above proof), which fits what is shown by @templatetypedef
回答3:
from T(n+1)=2T(n)+c we have :
T(n+1) + c = 2T(n) + 2c
T(n+1) + c = 2( T(n) + c )
T(n+1) + c = 2^n (T(0) + c)
T(n+1) = 2^n (T(0) + c) - c
which yields a Θ(2^n) complexity.
来源:https://stackoverflow.com/questions/12306735/time-bound-for-recursive-algorithm-with-constant-combination-time