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.
Answer: The subject of dynamic planning method, scan-by-column to the target point
The first line of the path weight is calculated by F (0), F (1), F (2), followed by a newline, then column by row to select the path, and so on, and finally reach the target point.
The code is as follows:
1 classSolution {2 Public:3 intMinpathsum (vector<vector<int> > &grid) {4 intm =grid.size ();5 intn = grid[0].size ();6 if(m==1&&n==1)7 returngrid[0][0];8 intminsum=grid[0][0];9vector<int>F;Ten f.resize (n); Onef[0]=grid[0][0]; A //set up an iterative structure - for(intI=1; i<n;i++){ -f[i]=grid[0][i]+f[i-1]; the } - for(intI=1; i<m;i++){ -f[0]+=grid[i][0]; - for(intj=1; j<n;j++){ +F[j]=min (f[j-1],F[J]) +Grid[i][j]; - } + } A at returnf[n-1]; - } -};
[Leetcode] Minimum Path Sum