This problem is not difficult, you can use DFS to do, you can also use dynamic planning, but obviously DFS performance is inferior to DP.
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.
Dynamic planning:
Use dis[x][y] to indicate the shortest distance to reach (x, y), because only right and down, so the smaller values of dis (x, y) = Dis[x-1][y] and dis[x][y-1] plus a (x, y). Final conversion to DIS (m-1,n-1)
Class Solution {public: int minpathsum (vector<vector<int> > &grid) { int mm=grid.size (); int nn=grid[0].size (); vector<vector<int> > Dis; Vector<int> Vec; Vec.push_back (Grid[0][0]); for (int i=1;i<nn;i++) { vec.push_back (vec[i-1]+grid[0][i]); } Dis.push_back (VEC); for (int i=1;i<mm;i++) { vec.clear (); for (int j=0;j<nn;j++) { if (j==0) vec.push_back (Dis[i-1][j]+grid[i][j]); else vec.push_back (min (dis[i-1][j],vec[j-1]) +grid[i][j]); } Dis.push_back (VEC); } return dis[mm-1][nn-1];} ;
In addition to this, you should pay attention to a lot of details, several submissions can not be passed because the relationship between VEC and dis is not handled well. Long time no use of C + + to do the problem, vector has not been the push value is not through direct access to the subscript to assign value, which requires special attention.
"Leetcode" "Python" Minimum Path Sum