64. 最小路徑和(python3)
阿新 • • 發佈:2021-01-13
技術標籤:leetcode mediumDPleetcode
題目:https://leetcode-cn.com/problems/minimum-path-sum/
給定一個包含非負整數的 mxn網格grid ,請找出一條從左上角到右下角的路徑,使得路徑上的數字總和為最小。
說明:每次只能向下或者向右移動一步。
示例 1:
輸入:grid = [[1,3,1],[1,5,1],[4,2,1]]
輸出:7
解釋:因為路徑 1→3→1→1→1 的總和最小。
示例 2:
輸入:grid = [[1,2,3],[4,5,6]]
輸出:12
提示:
m == grid.length
n == grid[i].length
0 <= grid[i][j] <= 100
解題思路:
動態規劃類題目如果沒有思路可先參考https://blog.csdn.net/anningne/article/details/111869155,瞭解了大致方法後參考方格類https://blog.csdn.net/anningne/article/details/112284336
此題轉移方程dp[i][j] = min{dp[i-1][j], dp[i][j-1]}+grid[i][j],初始值為最上方一行和最左邊一列,i==0時賦值為dp[i][j] = dp[i][j - 1] + grid[i][j],j==0時賦值為dp[i][j] = dp[i - 1][j] + grid[i][j]
程式碼:
class Solution: def minPathSum(self, grid: List[List[int]]) -> int: m = len(grid) n = len(grid[0]) dp = [[0]*n for _ in range(m)] for i in range(m): for j in range(n): if(i==0): if(j == 0): dp[i][j] = grid[i][j] else: dp[i][j] = dp[i][j - 1] + grid[i][j] elif(j==0): dp[i][j] = dp[i - 1][j] + grid[i][j] else: dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j] return dp[m - 1][n - 1]
測試:
if __name__ == "__main__":
grid = [[1,2,3],[4,5,6]]
res = Solution().minPathSum(grid)
print(res)