title :
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.
code : OJ Test via runtime:102 ms
1 classSolution:2 #@param grid, a list of lists of integers3 #@return An integer4 defminpathsum (Self, grid):5 #None case6 ifGrid isNone:7 returnNone8 #store each step on matrix9Step_matrix=[[0 forIinchRange (len (grid[0))] forIinchRange (len (GRID))]Ten #First Row OneTmp_sum =0 A forIinchRange (len (grid[0)): -Tmp_sum = Tmp_sum +Grid[0][i] -Step_matrix[0][i] =Tmp_sum the # First Line -Tmp_sum =0 - forIinchRange (len (grid)): -Tmp_sum = Tmp_sum +Grid[i][0] +Step_matrix[i][0] =Tmp_sum - #Dynamic Program other positions in Gird + forRowinchRange (1, Len (GRID)): A forColinchRange (1, Len (Grid[0])): atStep_matrix[row][col]=grid[row][col]+min (step_matrix[row-1][col],step_matrix[row][col-1]) - #return the minimun sum of path - returnStep_matrix[len (GRID) -1][len (Grid[0])-1]
Ideas :
The general idea of dynamic programming. See http://www.cnblogs.com/xbf9xbf/p/4250359.html for details.
It is important to note that the dynamic planning iteration condition Step_matrix[][]=grid[][]+min (...)
Min inside must be step_matrix corresponding to the element of the position. The first time a grid corresponding element, without AC, modified after the second AC.
Leetcode "Minimum Path Sum" Python implementation