Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Example:
Input: [ [1,3,1], [1,5,1], [4,2,1] ] Output: 7 Explanation: Because the path 1→3→1→1→1 minimizes the sum.
LeetCode:链接
动态规划的特点要求利用到上一次的结果,是一种特殊的迭代思想,动态规划的关键是要得到递推关系式。对于本题,从原点到达(i, j)的最小路径等于 :原点到达(i-1, j)最小路径与到达(i, j-1)最小路径中的最小值,即 dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1]。而且本题也可以不申请额外空间,直接在grid中修改参数即可,这使得空间复杂度得到了有效的利用,这类做法在实际场景中常常被用到。
class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
m = len(grid)
n = len(grid[0])
dp = [[0] * n for i in range(m)]
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
dp[i][j] = grid[i][j]
elif i == 0 and j > 0:
dp[i][j] = dp[i][j-1] + grid[i][j]
elif j == 0 and i > 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]