leetcode【中等】64、最小路径和

在这里插入图片描述
思路:动态规划

当 i>0 且 j=0时,dp[i][0]=dp[i-1][0]+grid[i][0]
当 i=0 且 j>0时,dp[0][j]=dp[0][j-1]+grid[0][j]
当 i>0 且 j>0 时,dp[i][j]=min(dp[i-1][j],dp[i][j-1])+grid[i][j]
class Solution:
    def minPathSum(self, grid: List[List[int]]) -> int:
        rows, columns = len(grid), len(grid[0])
        dp = [[0 for _ in range(columns)] for _ in range(rows)]
        dp[0][0] = grid[0][0]

        for i in range(1, rows):
            dp[i][0] = dp[i - 1][0] + grid[i][0]
        for j in range(1, columns):
            dp[0][j] = dp[0][j - 1] + grid[0][j]
        for i in range(1, rows):
            for j in range(1, columns):
                dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]
        return (dp[rows-1][columns-1])

猜你喜欢

转载自blog.csdn.net/qq_40707462/article/details/113345396