[Leetcode] (python): 064-minimum Path Sum

Source: Internet
Author: User

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

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.