64. Minimum Path Sum

Approach 1: Dynamic Programming to keep track of Path Sums

class Solution(object):
    def minPathSum(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        m = len(grid)
        if m > 0:
            n = len(grid[0])
        else:
            return 0
        dp = [[0] * n for _ in range(m)]
        dp[0][0] = grid[0][0]
        for i in range(1, m):
            dp[i][0] = grid[i][0] + dp[i-1][0]
        for j in range(1, n):
            dp[0][j] = grid[0][j] + dp[0][j-1]
        for i in range(1, m):
            for j in range(1, n):
                dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1])
        return dp[m-1][n-1]

We will initialize a 2D array named dp with zeros as always. The path sum for position (0,0) will obviously be grid[0][0]. For the first row the sum to position dp[0][j] will be the sum of all dp[0][k] where k < j. Similarly for the first column the sum to position dp[i][0] will be the sum of all dp[k][0] where k < i.

After that we simply have to iterate through the array and make sure each time to update the path sum by adding grid[i][j] to the minimum of dp[i-1][j] and dp[i][j-1] and store it in dp[i][j]

Last updated