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:

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

class Solution(object):
    def minPathSum(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        n = len(grid)
        m = len(grid[0])
        # 初始化二维数组
        dp = [[0 for _ in xrange(m)] for _ in xrange(n)]
        # 遍历二维数组
        for i in xrange(0, n):
            for j in xrange(0, m):
                if i == 0 and j == 0:
                    dp[0][0] = grid[0][0]
                # 上边只有一条路径可走,上边一行等于前面的格子相加
                elif i == 0:
                    dp[i][j] = dp[i][j-1] + grid[i][j]
                # 左边之后一条路径可走,左边的一行等于前面的格子相加
                elif j == 0:
                    dp[i][j] = dp[i-1][j] + grid[i][j]
                #其余有2条路径可走,取最小值
                else:
                    dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]
        return dp[n-1][m-1]
原文地址:https://www.cnblogs.com/boluo007/p/12421327.html