Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are tail recursion and dynamic programming the same?

I was programming Fibonacci numbers using tail recursion and it seems like the idea behind it is same as Dynamic programming. So are they same? or rather there is some amount of similarity between them? If not when are the cases when they get different?

like image 496
gizgok Avatar asked Sep 29 '12 04:09

gizgok


People also ask

What is the difference between recursion and dynamic programming?

Recursion takes time but no space while dynamic programming uses space to store solutions to subproblems for future reference thus saving time.

Are all recursive problems dynamic programming?

Dynamic programming cannot be used with every recursive solution. According to the definition, the problem must contain two properties to be considered viable for dynamic programming: Overlapping subproblems. Optimal substructure.

What is the opposite of tail recursion?

So a non-tail recursive function would be any function where you do anything after the recursive call (or there are even multiple recursive calls that aren't mutually exclusive). Usually that means applying some other function to the result of the recursive function after the recursive function returns.

What is tail recursion in programming?

Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. For example the following C++ function print() is tail recursive. Java.


2 Answers

The terms themselves, although related, are not equivalent by any means:

  • Dynamic programming is a problem solving methodology which can be implemented with or without using tail recursion. More generically, it requires "memoization".

  • Tail recursion is a common way to implement a dynamic programming algorithm, because it specifically applies memoization logic to a specific field.

like image 177
jayunit100 Avatar answered Nov 22 '22 11:11

jayunit100


I can see why you're asking this question. The idea behind dynamic programming is to break a problem into smaller problems, and this is the exact same idea behind many recursive (tail or not) functions.

This is really an apples to oranges kind of comparison that has plenty of good answers, but here's one thing that makes you realize why it's so hard to compare the two ideas: in some languages, including Java, you technically can't use tail recursion. As you might know, a tail recursive function doesn't store a stack of results from its calls and use them later. In Java, however, a stack trace is maintained for every method call. This uses stack space, and can stack overflow if it runs too many times. Therefore, any Java methods that might look tail recursive actually aren't.

like image 37
Chris Avatar answered Nov 22 '22 10:11

Chris