I am stuck by analyzing the time complexity of the following algorithm:
def fun (r, k, d, p):
if d > p:
return r
if d = 0 and p = 0:
r <- r + k
return r
if d > 0:
fun (r, k + 1, d - 1, p)
if p > 0:
fun (r, k - 1, d, p - 1)
The root call will be fun (0, 0, n, n)
, and n
is the size of the problem.
I guess that: The recurrence relation is $ T(n, n) = T(n-1, n) + T(n, n-1)$, which is equivalent to $T(2n) = 2T(2n-1) \iff T(m) = 2T(m - 1)$, and so $O(2^m) \iff O(4^n)$.
Is my analysis correct (I know it's not very complete and exact)? If it does have serious flaw, please point it out or show me a correct and complete proof on the time complexity of this algorithm.
d>0
andp>0
. You don't show what the function returns if we reach the 3rd and 4th if statements. Did you mean to have areturn
statement after each recursive invocation offun
? (did you meanfun (r, k + 1, d - 1, p)
to bereturn fun (r, k + 1, d - 1, p)
?) Or did you mean to have areturn
statement at the very end of the function body? Please edit your pseudocode to clarify and make sure you show what this returns in all possible cases. $\endgroup$d<=p
andd>0
andp>0
all hold. What is supposed to happen? Does the algorithm make 2 recursive invocations to the function? Or does it recursively invokefun(r, k + 1, d - 1, p)
and then immediately return, without recursively invokingfun(r, k - 1, d, p - 1)
? If I take your pseudocode literally, it appears that it makes 2 recursive invocations and then returns with an undefined return value -- but that seems odd and makes me wonder if there's a typo/bug in the pseudocode. $\endgroup$