It can be written recursively and concisely, but Will time out.
Dp. This problem needs to be calculated from the back. The small scale in the bottom right corner is known, and the boundary is also very obvious. It is the last row and the last column, the restriction on the walking direction determines that the routing of these locations is unique and can be calculated first. And then continue to calculate.
Use distance [I] [j] To save the shortest distance from the current position to the bottom right corner, the state transition equation selects a small one from distance [I + 1] [j] and distance [I] [j + 1], and then adds its own.
The code is easy to understand. This is the charm of dp. Space can be optimized, because the current status is only related to the last row and the next column.
class Solution {public: int minPathSum(vector<vector<int> > &grid) { int erow = grid.size(); if(erow<=0) return 0; int ecolumn = grid[0].size(); if(ecolumn<=0) return 0; if(erow==1&&ecolumn==1) return grid[0][0]; vector<int> tpres(ecolumn, 0); vector<vector<int> > distance(erow, tpres); distance[erow-1][ecolumn-1] = grid[erow-1][ecolumn-1]; for(int i=erow-2;i>=0;i--) distance[i][ecolumn-1] = distance[i+1][ecolumn-1] + grid[i][ecolumn-1]; for(int i=ecolumn-2;i>=0;i--) distance[erow-1][i] = distance[erow-1][i+1] + grid[erow-1][i]; for(int i=erow-2;i>=0;i--){ for(int j=ecolumn-2;j>=0;j--){ distance[i][j] = min(distance[i+1][j], distance[i][j+1])+grid[i][j]; } } return distance[0][0]; }};