Lecture 18: Dynamic Programming III: Previously
Lecture 18: Dynamic Programming III: Previously
Lecture 18: Dynamic Programming III: Previously
006
Massachusetts Institute of Technology November 13, 2018
Instructors: Zachary Abel, Erik Demaine, Jason Ku Lecture 18: Dynamic Programming III
Previously
• Recurrence: Fibonacci, DAG Relaxation, Rod cutting
• State topological order to argue relations are acyclic and form a DAG
Edit Distance
• Can modify a string using single character edit operations:
– Delete a character
– Replace a character with another character
– Insert a character between two characters
• Can transform A into B in O(max(|A|, |B|)) edit operations. What is fewest?
• Input: two strings A and B, Output: minimum number of edit operations to change A to B
• Example: A = "dog", B = "dingo" minimum is 3 edits
1. Subproblems
• Modify A until its last character matches last in B (A[i] is ith letter in A, from 1 to |A|)
• x(i, j): minimum number of edits to transform prefix ending at A[i] into prefix ending at B[j]
2. Relate
• If A[i] = B[j], then match!
• Otherwise, need to edit to make last element from A equal to B[j]
• Edit is either an insertion, replace, or deletion (Guess!)
• Deletion removes A[i]
• Insertion adds B[j] to start of prefix ending at A[i], then removes it and B[j]
• Replace changes A[i] to B[j] and removes both A[i] and B[j]
x(i − 1, j − 1) if A[i] = B[i]
• x(i, j) =
1 + min(x(i − 1, j), x(i, j − 1), x(i − 1, j − 1)) otherwise
• Subproblems x(i, j) only depend on strictly smaller i and j, so acyclic
3. Base
• x(i, 0) = i, x(0, j) = j (need many insertions or deletions)
4. Solution
• Solve subproblems via recursive top down or iterative bottom up
• Solution to original problem is x(|A|, |B|)
• (Can store parent pointers to reconstruct edits transforming A to B)
5. Time
• # subproblems: (|A| + 1)(|B| + 1)
• work per subproblem: O(1)
• O(|A||B|) running time
Lecture 18: Dynamic Programming III 3
Arithmetic Parenthesization
• Input: arithmetic expression containing n integers, with integers ai and ai+1 separated by
binary operator oi (a, b) from {+, ×}
1. Subproblems
2. Relate
3. Base
• x(i, i) = ai
4. Solution
5. Time
1. Subproblems
2. Relate
3. Base
• x(i, i, s) = ai
4. Solution
5. Time