menu

[LeetCode] 064. Minimum Path Sum

Problem (Medium)

064. 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:

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

Approach 1: (My Solution - DP)

Idea

  • State update: dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1]);
  • Initial state: each item is the sum from the first to current index items in grid.

Solution

class Solution1:
    def minPathSum(self, grid):
        """ 
        :type grid: List[List[int]]
        :rtype: int
        """
        m, n = len(grid[0]), len(grid)
        dp = [[0 for _ in range(m)] for  _ in range(n)]
        dp[0][0] = grid[0][0]
        for i in range(1, n): 
            dp[i][0] = grid[i][0] + dp[i-1][0]
        for j in range(1, m): 
            dp[0][j] = grid[0][j] + dp[0][j-1]
        print('start dp:', dp) 
        for i in range(1, n): 
            for j in range(1, m): 
                dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1])
        print('end dp:', dp) 
        return dp[-1][-1]

Complexity

  • Time: $O(mn)$
  • Space: $O(mn)$



KF

Comments