80 likes | 103 Vues
Dynamic Programming & Memoization. When to use?. Problem has a recursive formulation Solutions are “ordered” Earlier vs. later recursions. Get the recursion right!. If you’re not given the recursive solution explicitly, implement it Try on small cases (and “medium” ones)
E N D
When to use? • Problem has a recursive formulation • Solutions are “ordered” • Earlier vs. later recursions
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
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
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…
Dynamic Programming • Code is now rewritten • Replace recursion by loop • From “end cases” toward more complex ones
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)
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