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.
思路:
这题不要想得太复杂,什么搜索策略什么贪心什么BFS DFS。其实就是个DP基础题,迭代从上到下从左往右计算每个格子的距离就行了,目标是计算右下角的格子,没必要开二维数组,每次只需要更新一个滚动行即可。可以跟Unique Paths II对比着看看。
状态方程:Min[i][j] = min(Min[i-1][j], Min[i][j-1]) +A[i][j];
int minPathSum(vector<vector<int> > &grid) {
int row = grid.size();
if(row == ) return ;
int col = grid[].size();
if(col == ) return ; vector<int> steps(col, INT_MAX);//初始值是INT_MAX, 因为第一次更新steps[j]会调用min函数
steps[] = ;
for(int i = ; i < row; i++){
steps[] = steps[] + grid[i][];
for(int j = ; j < col; j++) {
steps[j] = min(steps[j], steps[j-]) + grid[i][j];
}
}
return steps[col-];
}