首页 > 其他 > 详细

leetcode 64. Minimum Path Sum

时间:2019-04-30 17:59:40      阅读:114      评论:0      收藏:0      [点我收藏+]

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.

dp
class Solution(object):
    def minPathSum(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        if not grid or not grid[0]:
            return 0
        m=len(grid)
        n=len(grid[0])
        dp=[[0 for c in range(n)] for r in range(m) ]
        dp[0][0]=grid[0][0]
        for i in range(1,len(grid[0])):
            dp[0][i]=dp[0][i-1]+grid[0][i]
        for i in range(1,len(grid)):
            dp[i][0]=dp[i-1][0]+grid[i][0]
        for i in range(1,m):
            for j in range(1,n):
                dp[i][j]=min(dp[i-1][j],dp[i][j-1])+grid[i][j]
        return dp[m-1][n-1]

 



leetcode 64. Minimum Path Sum

原文:https://www.cnblogs.com/sharon0/p/10797010.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!