码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 64. Minmum Path Sum

时间:2017-01-25 14:28:52      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:else   ber   either   leetcode   pre   sum   lis   nim   src   

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.

思路:一个很典型的DP问题。由于只能向下或者右走,所以通过 [i,j] 这个点的最短路径,要么是从[i-1,j]过来,要么从[i,j-1]过来。注意当i=0和j=0时这两个边界特例。

技术分享

 1 class Solution(object):
 2     def minPathSum(self, grid):
 3         """
 4         :type grid: List[List[int]]
 5         :rtype: int
 6         """
 7         m = len(grid)
 8         n = len(grid[0])
 9         minSum = [[0]*n for x in range(m)]
10         
11         for i in range(m):
12             for j in range(n):
13                 if i == 0 and j == 0:
14                     minSum[0][0] = grid[0][0]
15                 elif i == 0:
16                     minSum[i][j] = minSum[i][j-1] + grid[i][j]
17                 elif j == 0:
18                     minSum[i][j] = minSum[i-1][j] + grid[i][j]
19                 else:
20                     minSum[i][j] = min(minSum[i-1][j], minSum[i][j-1]) + grid[i][j]
21         
22         return minSum[-1][-1]

 

Leetcode 64. Minmum Path Sum

标签:else   ber   either   leetcode   pre   sum   lis   nim   src   

原文地址:http://www.cnblogs.com/lettuan/p/6349403.html

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