题目描述

给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。

说明:每次只能向下或者向右移动一步。

示例:

输入:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
输出: 7
解释: 因为路径 1→3→1→1→1 的总和最小。

python代码

动态规划+一维数组

class Solution:
def minPathSum(self, grid):
m, n = len(grid), len(grid[0])
grid_sum = sum([sum(suba) for suba in grid])
cur = [grid_sum for i in range(n+1)]
cur[0] = grid[0][0]
for i in range(1, n):
cur[i] = cur[i-1]+grid[0][i]
for i in range(1, m):
for j in range(n):
cur[j] = min(cur[j], cur[j-1]) + grid[i][j]
print(cur)
return cur[-2]

Leetcode题目59. 螺旋矩阵 II_一维数组

Reference

​https://leetcode-cn.com/problems/minimum-path-sum/solution/zui-xiao-lu-jing-he-dong-tai-gui-hua-gui-fan-liu-c/​