80 likes | 110 Views
Discover the power of dynamic programming and memoization techniques in solving complex problems efficiently. Learn when to use recursive formulations, ordered solutions, and how to implement memoization for a quick speedup. Dive into the structures and examples to enhance your problem-solving skills.
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