Dynamic programming is a technique for solving problems with overlapping sub problems. Typically, these sub problems arise from a recurrence relating a given problem’s solution to solutions of its smaller sub problems.
Rather than solving overlapping sub problems again and again, dynamic programming suggests solving each of the smaller sub problems only once and recording the results in a table from which a solution to the original problem can then be obtained.
The difference between Dynamic Programming and straightforward recursion is in memoization of recursive calls. If the sub problems are independent and there is no repetition then memoization does not help.
In this method, the recursive call is made only if n is
neither 1 not 0. So there occurs a situation where recursive
calls has to be made for same value of n but at different
instance.
Suppose we calculate Fib(4): (i) The
recursive calls made in root function are - Fib(3) and
Fib(2). (ii) The recursive calls made in
Fib(3) are - Fib(2) and Fib(1). (iii) The
recursive calls made in Fib(2) are - Fib(1) and Fib(0).
Notice that the the recursive call for n=2 is made twice
here and this situation occurs for other values of n also.
The simple solution is to memoize the newly calculated value
for n as shown in next step.
Here, we see that if memo[n] is not null then it returns
the value stored in it which prevents from making a new
recursive call.
It is top-down dp because the problem is broken into sub
problems, each of these sub problems is solved, and the
solutions are remembered in case they need to be solved
again.
Here, we see that if memo[n] is calculated just by
adding the previous two integers stored in that array.
It is bottom-up dp because these methods start with
lower values of input and keep building the solutions
for higher values.
That's it from this blog post. If you liked it then do share this blog with your friends or people who wanna get into programming world. Thank You!