Leetcode's Minimum Path Sum

Source: Internet
Author: User

Title Description:

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.

Given a m*n rectangle a, calculate each number from a[0][0] to A[m][n to add up to the smallest and. Note that you can only find the next number down or right at a time.

Analysis:

Always look in the lower right corner. Before you see a question, calculate how many ways to n*n the shortest distance from the upper left corner to the lower corner of the square. Let's look at the problem first.

Assume that the value of a[i][j] is equal to A[I-1][J] + a[j-1][i] in the 4*4 lattice, as shown in:

1 1 1 1

1 2 3 4

1 3 6 10

1 4 10 20

The shortest path shown above is the number of ways to go.

Then in the calculation from the upper left to the lower right corner of the smallest number and when the idea of dynamic planning, each step of the minimum value, depending on its left and top of the minimum value,

We set M[I][J] is to go to the a[i][j] when the smallest element and, by the above can be drawn,

M[i][j] = min (M[i-1][j]+a[i][j], m[i][j-1]+a[i][j])

Where: m[i][0] = a[i][0] m[0][j] = a[0][j]

The code is as follows:

1 classsolution (object):2     defminpathsum (Self, grid):3         """4 : Type Grid:list[list[int]]5 : Rtype:int6         """7n =len (GRID)8         ifn = =0:9             return0Tenm =Len (grid[0]) Onea = [[0] forIinchRange (m)] forJinchrange (n)] AA[0][0] =Grid[0][0] -          forJinchRange (1, m): -A[0][J] = a[0][j-1] +Grid[0][j] the          forIinchRange (1, N): -A[i][0] = a[i-1][0] +Grid[i][0] -          forIinchRange (1, N): -              forJinchRange (1, m): +A[i][j] = min (a[i-1][j]+grid[i][j], a[i][j-1]+Grid[i][j]) -         returnA[N-1][M-1]



Leetcode's 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.