Leetcode---64. Minimum Path Sum

Source: Internet
Author: User

Topic Link: Minimum Path Sum

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.

The requirement of this problem is to find the smallest path from the upper left corner to the lower right corner in the m*n grid. Only 1 cells can be moved downward or right at a time.

This is a dynamic programming problem, because each time only downward or right movement, so [I, j] position of the smallest path and equal to [I, j-1] and [I-1, J] in the small plus [I, j] position value. So the recursive formula is grid[i][j] + = min (Grid[i][j-1], grid[i-1][j]).

Time complexity: O (MN)

Space complexity: O (MN)

1 class Solution2 {3  Public:4     int Minpathsum(Vector<Vector<int> > &Grid)5     {6         7         if(Grid.size() == 0 || Grid[0].size() == 0)8             return 0;9         Ten          for(int I = 0; I < Grid.size(); ++ I) One              for(int J = 0; J < Grid[I].size(); ++ J) A             { -                 if(I == 0 && J == 0) ///The point in the upper left corner does not handle -                     Continue; the                 Else if(I == 0) //Processing left Border -                     Grid[I][J] += Grid[I][J - 1]; -                 Else if(J == 0) //Handle the above boundary -                     Grid[I][J] += Grid[I - 1][J]; +                 Else -                     Grid[I][J] += min(Grid[I - 1][J], Grid[I][J - 1]); +             } A          at         return Grid[Grid.size() - 1][Grid[0].size() - 1]; -     } - };

Reprint please indicate source: Leetcode---64. Minimum Path Sum

Leetcode---64. 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.