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])
 
 
class Solution:
    def minPathSum(self, grid: List[List[int]]) -> int:
        n1 = len(grid)
        n2 = len(grid[0])
        

        dp = [[0]*n2 for _ in range(n1)]
        dp[0][0] = grid[0][0]
        for i in range(1,n1):
            dp[i][0] = dp[i-1][0] + grid[i][0]
             
        for j in range(1,n2):
            dp[0][j] = dp[0][j-1] + grid[0][j]
        
        for i in range(1,n1):
            for j in range(1,n2):
                dp[i][j] = grid[i][j] + min(dp[i-1][j],dp[i][j-1])
        return dp[n1-1][n2-1]

 

posted @ 2018-03-31 14:31  乐乐章  阅读(315)  评论(0编辑  收藏  举报