Leetcode brushing record-64. The minimum path and

Insert picture description here
Since this problem involves solving the problem of dependency overlap,
the optimal path to the last grid depends on the optimal path to the "directly above" and "positive left" grids of the last grid.

So use dynamic programming decisively

The sub-problem is the optimal path to the lattice [I] [J]. The
state transition equation can be found in the code comments

class Solution:
    def __init__(self):
        self.newgrid = []
        self.grid = []
    def minPathSum(self, grid: List[List[int]]) -> int:
        m = len(grid)#行数
        n = len(grid[0])#列数
        if m == 1 and n == 1:
            return grid[0][0]
        elif (m == 1 and n != 1):
            return sum(grid[0])
        elif (m != 1 and n == 1):
            res = 0
            for i in range(m):
                res += grid[i][0]
            return res
        
        #以下m和n均大于1
        self.grid = grid
        newlist = []
        for i in range(m):
            templist = []
            for j in range(n):
                templist.append(-1)
            newlist.append(templist)
        #以下为状态转移方程
        for i in range(m):
            #templist = []
            for j in range(n):
                if i == 0 and j == 0:#dp[0][0] = grid[0][0]
                    newlist[i][j] = grid[0][0]
                elif i == 0 and j != 0:#对第一行,dp[0][j] = dp[0][j-1] + grid[0][j]
                    newlist[i][j] = newlist[0][j-1] + grid[0][j]
                elif i != 0 and j == 0:#对第一列,dp[i][0] = dp[i-1][0] + grid[i][0]
                    newlist[i][j] = newlist[i-1][0] + grid[i][0]

        for i in range(1,m):
            for j in range(1,n):
            	#对其它位置的一般格子(不位于左边界和上边界上的格子)
            	#有dp[i][j] = min(dp[i-1][j],dp[i][j-1]) + grid[i][j]
                newlist[i][j] = min(newlist[i-1][j], newlist[i][j-1]) + grid[i][j]
        return newlist[m-1][n-1]
Published 43 original articles · praised 14 · 20,000+ views

Guess you like

Origin blog.csdn.net/weixin_41545780/article/details/105103501