SDE & MLE Prep

64. Minimum Path Sum

Problem

Moving only right or down, find the path from the top-left to the bottom-right of grid (non-negative numbers) with the smallest sum of cell values, and return that sum.

Example: [[1,3,1],[1,5,1],[4,2,1]] → 7 (1 → 3 → 1 → 1 → 1)

dp[r][c] = grid[r][c] + min(dp[r−1][c], dp[r][c−1]), with one row.

Complexity: O(m·n) time, O(n) space.

class Solution:
    def minPathSum(self, grid: List[List[int]]) -> int:
        n = len(grid[0])
        row = [float("inf")] * n
        row[0] = 0
        for r in grid:
            row[0] += r[0]
            for c in range(1, n):
                row[c] = r[c] + min(row[c], row[c - 1])
        return row[-1]