https://leetcode.com/problems/minimum-path-sum/
The main idea: give a m*n table, which stores a m*n non-negative integer, in the upper left corner of the path to the lower right corner (requires only one step down or to the right), to find out the path of the smallest number of numbers.
Problem-solving ideas: using F[I][J] to indicate from the origin to the first row of the J column of the smallest sum, then f[i][j] The previous step is either f[i][j-1], or f[i-1][j], select the minimum value and the step itself to add the number, you can get f[i][j]. But note that the boundary of the table should be handled in a special way, with only one direction to go.
As can be seen from the above, the problem is a typical dynamic programming.
The code is as follows:
1 classSolution {2 Public:3 intMinpathsum (vector<vector<int> >&grid) {4 introw =grid.size ();5 intCol = grid[0].size ();6 if(Row = =0)return 0;7 8 intF[row][col];9 for(inti =0; i < row; i++)Ten { One for(intj =0; J < Col; J + +) A { -F[I][J] =Grid[i][j]; - } the } - for(inti =0; i < row; i++) - { - for(intj =0; J < Col; J + +) + { - if(I >=1&& J >=1) + { AF[I][J] + = min (f[i-1][J], f[i][j-1]); at } - Else if(I >=1) F[i][j] + = f[i-1][j]; - Else if(J >=1) F[i][j] + = f[i][j-1]; - } - } - returnf[row-1][col-1]; in } -};
Minimum Path Sum