64. 最小路径和-python

思路:经典的dp题目,应该是新建一个dp表,dp[i][j]表示从左上角到grid[i][j]的最短路径,因为只能往下和往右走,因此dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j],经过压缩后可以使用一维的dp表,但是更新每个dp[i][j]只需要用到当前的grid[i][j],因此可以就把grid作为dp表,不用另外申请变量。

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

转载于:https://www.cnblogs.com/dolisun/p/11350492.html

你可能感兴趣的:(python)