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.
思路:本题的解题思路与《Unique Paths》一样,也是典型的动态规划问题。要求从左上角grid[0][0]到右下角grid[m-1][n-1]的路径最小值,可以从grid[m-1][n-1]开始,从右向左,从下到上的依次求出grid[i][j]到grid[m-1][n-1]的路径最小值。
设min[i][j]表示从grid[i][j]到grid[m-1][n-1]的最小值。因只能向下或者向右走,所以min[i][j] = grid[i][j]+min(min[i][j+1],min[i+1][j]),因此,只要求出了min[i][j+1]和min[i+1][j],就可以求出min[i][j]了。代码如下:
int minPathSum(int** grid, int gridRowSize, int gridColSize) { int i, j; for(i = gridRowSize-1; i >= 0; i--) { for(j = gridColSize-1; j >= 0; j--) { if(i == gridRowSize-1 && j == gridColSize-1) continue; if(i == gridRowSize-1) { grid[i][j] += grid[i][j+1]; continue; } if(j == gridColSize-1) { grid[i][j] += grid[i+1][j]; continue; } grid[i][j] += min(grid[i+1][j], grid[i][j+1]); } } return grid[0][0]; }