Minimum Path Sum
Difficulty: Medium · Pattern: 2-D Dynamic Programming · LeetCode #64
Find a path from the top-left to the bottom-right of a grid of non-negative numbers, moving only right or down, that minimizes the sum of the numbers on it. Return that sum.
Examples
text
[[1,3,1],[1,5,1],[4,2,1]] → 7 (1→3→1→1→1)
[[1,2,3],[4,5,6]] → 12Hints
- To reach a cell you came from above or from the left. Pick the cheaper one.
Approach
dp[c] = grid[r][c] + min(dp[c] (from above), dp[c−1] (from the left)), with only one option on the first row and first column. A 1-D rolling array gives O(C) space. You could also overwrite grid in place for O(1) extra space, if mutating the input is allowed.
Because the moves only go right and down, the dependency graph is acyclic and row-major order is a valid topological order. With four-directional moves you'd need Dijkstra instead.
Complexity
Time: O(R·C). Space: O(C).
Python solution
def minPathSum(grid):
C = len(grid[0])
dp = [float('inf')] * C
dp[0] = 0
for row in grid:
dp[0] += row[0]
for c in range(1, C):
dp[c] = row[c] + min(dp[c], dp[c - 1])
return dp[-1]JavaScript solution
function minPathSum(grid) {
const C = grid[0].length, dp = new Array(C).fill(Infinity);
dp[0] = 0;
for (const row of grid) {
dp[0] += row[0];
for (let c = 1; c < C; c++) dp[c] = row[c] + Math.min(dp[c], dp[c - 1]);
}
return dp[C - 1];
}