题目来源:
https://leetcode.com/problems/minimum-path-sum/
题意分析:
给定一个m×n的非负矩阵,找到一条路使得从(0,0)到(m - 1,n - 1)经过的所有数字的和最小(类似上两题,只能向下和向上)。
题目思路:
和上一题类似,用一个二维矩阵a[i][j]代表从(0,0)到(i,j)的最小和。那么a[i][j] = min(a[i-1][j],a[i][j -1]) + nums[i][j]。那么这题也是一个动态规划问题,只需要把a的整个表打出来就可以了。时间复杂度是O(m×n)。
代码(Python):
1 class Solution(object): 2 def minPathSum(self, grid): 3 """ 4 :type grid: List[List[int]] 5 :rtype: int 6 """ 7 m,n = len(grid),len(grid[0]) 8 ans = [[0 for i in range(n)] for j in range(m)] 9 ans[0][0] = grid[0][0] 10 for i in range(m): 11 for j in range(n): 12 if i !=0 and j == 0: 13 ans[i][j] = ans[i-1][j] + grid[i][j] 14 elif i == 0 and j != 0: 15 ans[i][j] = ans[i][j - 1] + grid[i][j] 16 elif i != 0 and j != 0: 17 ans[i][j] = min(ans[i - 1][j],ans[i][j - 1]) + grid[i][j] 18 return ans[m - 1][n - 1]
转载请注明出处:http://www.cnblogs.com/chruny/p/5008373.html