借鉴了一下排行榜上大佬们的代码,简写了一下,虽然牺牲了一部分效率,但我觉得更 pythonic。

#
# 
# @param matrix int整型二维数组 the matrix
# @return int整型
#
class Solution:
    def minPathSum(self , matrix ):
        if not matrix:
            return 0

        dp = [0] * len(matrix[0])
        for i in range(len(matrix)):
            for j in range(len(matrix[i])):
                if not i or not j:
                    dp[j] = bool(i) * dp[j] + bool(j) * dp[j-1] + matrix[i][j]
                else:
                    dp[j] = min(dp[j], dp[j-1]) + matrix[i][j]
        return dp[-1]

然后我去 leetcode 逛了一圈,发现自己还是年轻了,淘到个理解更透彻的写法,简单到离谱:

class Solution:
    def minPathSum(self , matrix ):
        dp = [float('inf')] * (len(matrix[0])+1)
        dp[1] = 0
        for row in matrix:
            for i, num in enumerate(row):
                dp[i + 1] = min(dp[i], dp[i + 1]) + num
        return dp[-1]

https://leetcode-cn.com/problems/minimum-path-sum/solution/zui-xiao-lu-jing-he-by-leetcode-solution/507068