Dynamic Programming
Dynamic Programming
Dynamic Programming
Chapter 12
Acknowledgement
• I have used some slides from
– https://www.cis.upenn.edu/~matuszek/
– cit594-2014/Lectures/30-dynamic-
programming.ppt
– http://web.stanford.edu/class/cs97si/
Dynamic Programming
• Dynamic programming is a very powerful,
general tool for solving optimization problems.
• Once understood it is relatively easy to apply,
but many people have trouble understanding
it.
Greedy Algorithms
• Greedy algorithms focus on making the best
local choice at each decision point.
• For example, a natural way to compute a
shortest path from x to y might be to walk out
of x, repeatedly following the cheapest edge
until we get to y. WRONG!
• In the absence of a correctness proof greedy
algorithms are very likely to fail.
Problem:
Let’s consider the calculation of Fibonacci numbers:
7
Recursive Algorithm:
Fib(n)
{
if (n == 0)
return 0;
if (n == 1)
return 1;
Return Fib(n-1)+Fib(n-2)
}
8
Recursive Algorithm:
Fib(n)
{ It has a serious issue!
if (n == 0)
return 0;
if (n == 1)
return 1;
Return Fib(n-1)+Fib(n-2)
}
9
Recursion tree
10
Memoization:
Fib(n)
{
if (n == 0)
return M[0];
if (n == 1)
return M[1];
//Store the ${n}^{th}$ Fibonacci no. in memory & use previous results.
M[n] = M[n-1] + M[n-2]
Return M[n];
}
11
already calculated …
12
Dynamic programming
13
1-dimensional DP Problem
1-dimensional DP Problem
1-dimensional DP Problem
1-dimensional DP Problem
What happens when n is extremely large?
Tri Tiling
Tri Tiling
Tri Tiling
Finding Recurrences
Finding Recurrences
Extension
• Solving the problem for n x m grids, where n is
small, say n ≤ 10.
– How many subproblems do we consider?
Egg dropping problem
Egg dropping problem
Egg dropping problem
Egg dropping problem
Egg dropping problem
Egg dropping problem
Egg dropping problem
Egg dropping problem(n eggs)
Dynamic Programming Approach
• D[j,m] : There are j floors and m eggs. Like to find the
floors with the largest value from which an egg, when
dropped doesn’t crack.