首页 > 代码库 > [leetcode]Minimum Path Sum @ Python
[leetcode]Minimum Path Sum @ Python
原题地址:https://oj.leetcode.com/problems/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.
解题思路:这道题也是比较简单的动态规划,注意矩阵下标问题就行了。
代码:
class Solution: # @param grid, a list of lists of integers # @return an integer def minPathSum(self, grid): 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 i in range(1, m): 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]
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。