64. A minimum path and -python

Ideas: classic dp title, should be to create a new table dp, dp [i] [j] said we could only go to the right and down from the top left to the grid [i] [j] is the shortest path because, therefore dp [ i] [j] = min (dp [i-1] [j], dp [i] [j-1]) + grid [i] [j], after compression can be used one-dimensional dp table, but the update each dp [i] [j] only need to use the current grid [I] [J], it is possible to put a grid table dp, without applying additional variables.

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]
                

Guess you like

Origin www.cnblogs.com/dolisun/p/11350492.html