2D Dynamic Programming — Complete Guide
Master 2D DP: LCS, Edit Distance, grid path counting, matrix chain, interval DP, and stock patterns with 5-language templates.
webcoderspeed.com
7 articles
Master 2D DP: LCS, Edit Distance, grid path counting, matrix chain, interval DP, and stock patterns with 5-language templates.
Count paths from top-left to bottom-right moving only right or down. dp[i][j] = dp[i-1][j] + dp[i][j-1]. Math formula O(1) also works.
Count paths avoiding obstacle cells. Same DP but obstacles block cell (dp[i][j]=0) and obstacle at start/end returns 0.
Find minimum cost path from top-left to bottom-right moving right or down. dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1]).
Minimum path sum from top to bottom of triangle. Bottom-up DP: dp[j] = triangle[i][j] + min(dp[j], dp[j+1]).
Find minimum initial health to reach bottom-right dungeon cell. Solve backwards: dp[i][j] = min health needed at (i,j) to survive.
Find minimum sum falling path from top row to bottom row, moving to adjacent diagonal cells. DP row by row.