[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.

解题思路:这道题也是比较简单的动态规划,注意矩阵下标问题就行了。

代码:

[leetcode]Minimum Path Sum @ Python
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]
[leetcode]Minimum Path Sum @ Python

 

[leetcode]Minimum Path Sum @ Python,布布扣,bubuko.com

[leetcode]Minimum Path Sum @ Python

上一篇:jquery中bind和on的区别


下一篇:JavaScript模式 --- 札记