64. Minimum path sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time.

Example 1:

Input: grid = [[1,3,1],[1,5,1],[4,2,1]] Output: 7 Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.

  • code better dp
class Solution:
    def minPathSum(self, grid):
        m = len(grid)
        n = len(grid[0])
        for i in range(1, n):
            grid[0][i] += grid[0][i-1]
        for i in range(1, m):
            grid[i][0] += grid[i-1][0]
        for i in range(1, m):
            for j in range(1, n):
                grid[i][j] += min(grid[i-1][j], grid[i][j-1])
        return grid[-1][-1]
  • code naive dp
class Solution:
    def minPathSum(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        path = {(0,0):grid[0][0]}
        for x in range(m):
            for y in range(n):
                if x == 0 and y == 0: continue
                if x == 0:
                    path[(x, y)] = path[(x, y-1)] + grid[x][y]
                elif y == 0:
                    path[(x, y)] = path[(x-1, y)] + grid[x][y]
                else:
                    path[(x, y)] = min(path[(x, y-1)], path[(x-1, y)]) + grid[x][y]
        return path[(m-1, n-1)]