Source of the topic:
https://leetcode.com/problems/minimum-path-sum/
Test Instructions Analysis:
Given a nonnegative matrix of MXN, find a way to make all the numbers from (0,0) to (m-1,n-1) pass and the smallest (similar to the last two questions, only downward and upward).
Topic Ideas:
Similar to the previous question, use a two-dimensional matrix a[i][j] to represent the smallest and from (0,0) to (I,J). Then a[i][j] = min (a[i-1][j],a[i][j-1]) + nums[i][j]. So this is also a dynamic programming problem, just need to put a's entire table out on it. The complexity of Time is O (MXN).
Code (Python):
1 classsolution (object):2 defminpathsum (Self, grid):3 """4 : Type Grid:list[list[int]]5 : Rtype:int6 """7M,n =len (GRID), Len (grid[0])8ans = [[0 forIinchRange (n)] forJinchrange (m)]9Ans[0][0] =Grid[0][0]Ten forIinchRange (m): One forJinchrange (n): A ifI!=0 andj = =0: -ANS[I][J] = Ans[i-1][j] +Grid[i][j] - elifi = = 0 andJ! =0: theANS[I][J] = ans[i][j-1] +Grid[i][j] - elifI! = 0 andJ! =0: -Ans[i][j] = min (ans[i-1][j],ans[i][j-1]) +Grid[i][j] - returnANS[M-1][N-1]
View Code
Reprint Please specify source: http://www.cnblogs.com/chruny/p/5008373.html
[Leetcode] (python): 064-minimum Path Sum