Dynamic Programming 2D in Python
Chapter 58: Dynamic Programming 2D
4 short lessons, with 3D animations, quizzes and coding tasks.
The lessons
Paths through a grid
In a 2D DP the state is two numbers, here the square (r, c), and the table is a grid: every route to a square arrives from the square above it or the one to its left, so dp[r][c] is built from those two cells, filled row by row from the top-left.
Longest common subsequence
Let dp[i][j] be the LCS of the first i items of a and the first j items of b; if the last two items match they both join it, and if not, one of them is not in it, so drop each in turn and keep the better.
0/1 knapsack
In the 0/1 knapsack each item is taken whole or left behind, and dp[i][c] is the best value from the first i items in a bag of c kg: item i is either left out (dp[i − 1][c]) or, if it fits, taken (dp[i − 1][c − w] + v), and the table keeps the better.
Edit distance
The edit distance dp[i][j] between the first i letters of a and the first j of b comes from the last letters: if they agree they cost nothing, and if not, the last edit was a replace, a delete or an insert, so take 1 plus the cheapest of those three cells.