Dynamic programming
To recognize a dynamic programming problem, first ask whether it could be solved with backtracking: if the solution comes from a sequence of decisions, it fits a decision tree. There are clues in favor: that it asks for an optimum (the largest, the smallest, the fewest steps) and that the states fit in a list or matrix. And clues against: that it asks for every solution, or for specific permutations or combinations.
Solving a dynamic programming problem usually takes 3 steps. First, see what is decided at each step and define the state and the dp table. Second, find the optimal substructure and write the state transition equation. Third, set the boundary conditions and the order in which the table is filled. With that you can write the code directly, although it is often more natural to go through brute force and memoization first.
The example is the minimum path sum: an n Γ m grid with a cost in each cell, and a robot that goes from the top left to the bottom right, moving only down or right. At each step it decides down or right, so the state needs 2 variables: the row and the column, [i, j]. dp[i, j] is the minimum sum from [0, 0] to [i, j], and the dp table is the same size as the grid.
Cells in row 0 can only be reached from the left, and cells in column 0 only from above: those are the boundary conditions. With the grid [[1, 3, 1], [1, 5, 1], [4, 2, 1]], row 0 becomes 1, 4, 5 and column 0 becomes 1, 2, 6. Since each cell depends on the one above and the one to the left, it is walked with 2 for loops: the outer one over rows and the inner one over columns. That way, every value needed is already computed.
