You are on page 1of 6

DYNAMIC PROGRAMMING

DYNAMIC PROGRAMMING IS AN ALGORITHMIC PARADIGM THAT


SOLVES A GIVEN COMPLEX PROBLEM BY BREAKING IT INTO
SUBPROBLEMS AND STORING THE RESULTS OF SUBPROBLEMS
TO AVOID COMPUTING THE SAME RESULTS AGAIN

Solving a problem– 3 ways:


1. Recursion
2. Memoization
3. Bottom-up
Eg: Fibonacci series
 f(n) = f(n-1) + f(n-2) , where n>=2
f(1) = 1 and f(0) = 0
 f(n) = [0, 1, 1, 2, 3, 5, 8, 13, ….]

 Simple recursion:

int fib (int n)


{
if ( n<= 1)
return n;
return fib(n-1) + fib(n-2);
}
Optimal substructure:
If an optimal solution of the given problem can be obtained by
using optimal solution of its subproblems. Eg: Floyd-Warshall
Recurrence relation:
T(n) = T(n-1) + T(n-1) + O(1)

Time complexity = O(2n)

Solution:
Do not solve the same problem again,
just recall it rom memory.
Overlapping subproblems Two methods:
1. Memoization (Top-Down)
2. Tabulation (Bottom-Up)
Memoized solution
Algo fib(n, memo)
{
if memo[n] != null
return memo[n]
if n<=1
result = n
else
result = fib(n-1) + fib(n-2)
memo[n] = result
null null null null null null
return result
}
Tabulation
Algo fib(n)
{
if n<=1
result = n
int bottom_up[n+1];
bottom_up[0] = 0;
bottom_up[1] = 1;
for i from 2 upto n:
bottom_up[i] = bottom_up[i-1] + bottom_up[i-2] null null null null null null
return bottom_up[n];
}
Thank You

You might also like