[leetcode] 64. Minimum Path Sum @ python

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/86632049

原题

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.

解法

动态规划. 我们直接在grid上推导, 由于只能往下走或者往右走, 那么在第0行, grid[0][i]的最小和只能是它左边的格子的最小和加上它的值, 在第0列,grid[j][0]的最小和只能是它上面的格子的最小和加上它的值. 从第1行和第1列开始, grid[i][j]的最小和=min(它上面格子的最小和, 它左边格子的最小和) + grid[i][j], 如此可以推导出走到右下角的最小和.

Time: O(m*n)
Space: O(1)

代码

class Solution(object):
    def minPathSum(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        row, col = len(grid), len(grid[0])
        for i in range(1, col):
            grid[0][i] += grid[0][i-1]
        for j in range(1, row):
            grid[j][0] += grid[j-1][0]
        for r in range(1, row):
            for c in range(1, col):
                grid[r][c] = min(grid[r-1][c], grid[r][c-1]) + grid[r][c]
        return grid[-1][-1]

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/86632049