题目描述
给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。
说明:每次只能向下或者向右移动一步。
示例:
输入:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
输出: 7
解释: 因为路径 1→3→1→1→1 的总和最小。
动态规划
思路:
因为只能往右或者往下走,由此每个网格的最短路径和由上面网格或者左边网格决定,推出决策式子为:
dp[i][j] = grid[i][j] + min (dp[i-1][j], dp[i][j-1])
class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
n = len(grid)
m = len(grid[0])
dp = [[0 for i in range(m)] for i in range(n)]
for i in range(n):
for j in range(m):
if i == 0 and j == 0:
continue
elif i == 0 and j != 0:
grid[0][j] = grid[0][j-1]+grid[0][j]
elif i != 0 and j == 0:
grid[i][0] = grid[i-1][0] + grid[i][0]
else:
grid[i][j] = grid[i][j] + min(grid[i-1][j] , grid[i][j-1])
return grid[-1][-1]