64. Minimum Path Sum(最小走棋盘 动态规划)

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 1:

[[1,3,1],
 [1,5,1],
 [4,2,1]]
Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum.
 
走的方向决定了同一个位置不会走2次。
如果当前位置是(x,y)上一步来自哪呢?
上一步可能从左边【x-1,y】来,也可能从上边来[x,y-1] ,所以当前的最小路径就是 min(左边 + 当前值 , 上边+当前值) 
 
dp[0][0] = a[0][0]
dp[x][y] = min(dp[x-1][y]+a[x][y],+dp[x][y-1]+a[x][y])
 
 
 
 1 class Solution:
 2     def minPathSum(self, grid):
 3         """
 4         :type grid: List[List[int]]
 5         :rtype: int
 6         """
 7         dp = []
 8         for i in grid:
 9             dp.append(i)
10             
11         for i in range(len(grid)):
12             for j in range(len(grid[0])):
13                 if(i==0 and j ==0):
14                     dp[i][j] = grid[i][j]
15                 elif i==0 and j !=0 :
16                         dp[i][j] = dp[i][j-1] + grid[i][j]
17                 elif i!=0 and j==0:
18                         dp[i][j] = dp[i-1][j] + grid[i][j]
19                 else:
20                     dp[i][j] = min(dp[i-1][j]+grid[i][j],dp[i][j-1]+grid[i][j])
21         return dp[i][j]
22         
原文地址:https://www.cnblogs.com/zle1992/p/8682083.html