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