码迷,mamicode.com
首页 > 编程语言 > 详细

[leetcode]Minimum Path Sum @ Python

时间:2014-05-28 03:03:13      阅读:320      评论:0      收藏:0      [点我收藏+]

标签:style   c   class   blog   code   java   

原题地址: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.

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

代码:

bubuko.com,布布扣
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]
bubuko.com,布布扣

 

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

[leetcode]Minimum Path Sum @ Python

标签:style   c   class   blog   code   java   

原文地址:http://www.cnblogs.com/zuoyuan/p/3753611.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!