Presentation is loading. Please wait.

Presentation is loading. Please wait.

Dynamic Programming & Memoization. When to use? Problem has a recursive formulation Solutions are “ordered” –Earlier vs. later recursions.

Similar presentations


Presentation on theme: "Dynamic Programming & Memoization. When to use? Problem has a recursive formulation Solutions are “ordered” –Earlier vs. later recursions."— Presentation transcript:

1 Dynamic Programming & Memoization

2 When to use? Problem has a recursive formulation Solutions are “ordered” –Earlier vs. later recursions

3 Get the recursion right! If you’re not given the recursive solution explicitly, implement it Try on small cases (and “medium” ones) Make sure you have all base cases! Test data is often small enough

4 Memoization A quick and dirty speedup Uses the recursive algorithm almost directly Avoid if too many parameters Modify the recursive call to –Save its result –See if the result is computed before computing it

5 Structure of Memoization Int my-recursive-function (int param1, int param2){ //base cases go here //memoization addition if (table[param1][param2] != NONE) return table[param1][param2]; //continue with recursive solution…

6 Dynamic Programming Code is now rewritten Replace recursion by loop –From “end cases” toward more complex ones

7 Structure of Dynamic Program Initialize base cases in array (e.g. top, left border) Loop through array in a reasonable order –Goal: “recursive cases” already computed –If bases are top, left, then L->R, T->B OK Search array for final solution (if needed)

8 Example: String Editing (p.248-249) Strings across top and down left Base cases at borders –Empty string = length() insertions Step considers 3 options –Match last character –Add last character –Delete last character Final result at last char each string


Download ppt "Dynamic Programming & Memoization. When to use? Problem has a recursive formulation Solutions are “ordered” –Earlier vs. later recursions."

Similar presentations


Ads by Google