Dynamic Programming
Dynamic Programming
1. If n <= 1, return 1.
2. Else, return the sum of two preceding numbers.
3. The third term is sum of 0 (from step 1) and 1(from step 2), which is 1.
4. The fourth term is the sum of the third term (from step 3) and second term
(from step 2) i.e. 1 + 1 = 2.
5. The fifth term is the sum of the fourth term (from step 4) and third term (from
step 3) i.e. 2 + 1 = 3.
Hence, we have the sequence 0,1,1, 2, 3 . Here, we have used the results of
the previous steps as shown below. This is called a dynamic programming
approach.
F(0) = 0
F(1) = 1
var m = map(0 → 0, 1 → 1)
function fib(n)
return m[n]
function fib(n)
if n = 0
return 0
else
repeat n − 1 times
currFib = newFib
return currentFib
But not all problems that use recursion can use Dynamic Programming.
Unless there is a presence of overlapping subproblems like in the fibonacci
sequence problem, a recursion can only reach the solution using a divide and
conquer approach.
That is the reason why a recursive algorithm like Merge Sort cannot use
Dynamic Programming, because the subproblems are not overlapping in any
way.