I’m trying to analyze the performance a recursive program I wrote.
The basic code is
Cost(x)
{
1 + MIN(Cost(x-1), Cost(x-2), Cost(x-3))
}
I want to write a recurrence relation for the number of calls made to Cost(). How would I start this?
Something like T(x) = T(x/2). But I don’t think that’s right
Edit: I can represent this as a tree with a branching factor of 3 for each of the 3 recursive calls to Cost(). So would it would more accurately be T(x) = T(x/3)?
The number of calls made to Cost() would be:
So, for an input
x, Cost() was called once plus the amount of times it was called forx-1,x-2, andx-3. This is assuming that your solution does not use memoization. The recurrence relation is not pretty: http://www.wolframalpha.com/input/?i=T(x)+%3D+1+%2B+T(x-1)+%2B+T(x-2)+%2B+T(x-3)Using memoization, however, your “number of calls” becomes
C(x) = xbecause you only need to evaluateC(i)once for allibetween0andx. (Might beC(x) = x + 1, depending on your initial conditions)