Dynamic Programming
Dynamic Programming
Dynamic Programming
Fib(n)
{
if (n == 0)
return 0;
if (n == 1)
return 1;
Return Fib(n-1)+Fib(n-2)
}
Recursive Algorithm:
Fib(n)
{
if (n == 0)
return 0; It has a serious issue!
if (n == 1)
return 1;
Return Fib(n-1)+Fib(n-2)
}
Recursion tree
What’s the problem?
• Fib(n)
• {
• if (n == 0)
Memoization:
• return M[0];
• if (n == 1)
• return M[1];
• if (Fib(n-2) is not already calculated)
• call Fib(n-2);
• if(Fib(n-1) is already calculated)
• call Fib(n-1);
• //Store the ${n}^{th}$ Fibonacci no. in memory & use previous results.
• M[n] = M[n-1] + M[n-2]
• Return M[n];
•}
already calculated …
Dynamic programming
• Since exponential time is unacceptable for all but the smallest problems,
dynamic programming is sometimes essential.
Steps in Dynamic Programming
1. Characterize structure of an optimal solution.
2. Define value of optimal solution recursively.
3. Compute optimal solution values either top-down with caching or
bottom-up in a table.
4. Construct an optimal solution from computed values.
We’ll study these with the help of examples.