【LEETCODE】64-Minimum Path Sum

来源:互联网 发布:网络电影 罪 编辑:程序博客网 时间:2024/04/29 04:32

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right whichminimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.


题意:

给一个 m x n 的非负网格,从左上角到右下角 找到一个path 使得这条path上的所有数字的和最小

注意:

每次只能向下或者向右


思路:

动态规划


Python:

class Solution(object):    def minPathSum(self, grid):        """        :type grid: List[List[int]]        :rtype: int        """                m=len(grid)        n=len(grid[0])                dp=[[0 for i in range(n)] for j in range(m)]                dp[0][0]=grid[0][0]                for i in range(1,n):            dp[0][i]=dp[0][i-1]+grid[0][i]                for j in range(1,m):            dp[j][0]=dp[j-1][0]+grid[j][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]


0 0
原创粉丝点击