Leetcode "Minimum Path Sum" Python implementation

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.