Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use recursion or memoization for an algorithm?

If I have a choice to use recursion or memoization to solve a problem which should I use? In other words if they are both viable solutions in that they give the correct output and can be reasonably expressed in the code I'm using, when would I use one over the other?

like image 601
klyde Avatar asked Jan 26 '09 15:01

klyde


People also ask

Is memoization the same as recursion?

Memoization is a way to potentially make functions that use recursion run faster. As I'll show in an example below, a recursive function might end up performing the same calculation with the same input multiple times. This means it could end up taking longer than the iterative alternative.

When should you consider using recursive algorithms?

When should I use recursion? Recursion is made for solving problems that can be broken down into smaller, repetitive problems. It is especially good for working on things that have many possible branches and are too complex for an iterative approach .

Does memoization have to be recursive?

Recursion has absolutely nothing to do with memoization and dynamic programming; it is a completely separate concept.

Which algorithm uses memoization?

For Example, when we applied memoization to a recursive algorithm with O(2^n) complexity, we saw a massive performance boost. In this case, accessing a cache is much faster than repeating a calculation. Memoization allows us to use the recursive Fibonacci algorithm.


1 Answers

They are not mutually exclusive. You can use them both.

Personally, I'd build the base recursive function first, and add memoization afterwards, as an optimisation step.

like image 170
Jonathan Avatar answered Oct 09 '22 19:10

Jonathan