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.
Note: You can only move either down or right at any point in time.
很简单的DP问题,只要看下DP的经典例题,转配线调度问题之后,这道题就很简单了。
题中说道只能向下或者向右走,因此到终点[m][n]要么从上面[m][n - 1]走下来,要么从左边[m - 1][n]走过来,看这两条路那条更短,如果上面的短,那么将[m][n - 1]当做终点。继续做这样的操作(因为本题目满足最优子结构)
public int minPathSum(int[][] grid) {
if(grid == null){
return 0;
}
int row = grid.length;
int column = grid[0].length;
int max = row > column ? row : column;
int min = row + column - max;
int[][] result = new int[row][column];
result[0][0] = grid[0][0];
int i = 1;
for(; i < max; i++){
if(i < row){
result[i][0] = result[i - 1][0] + grid[i][0];
}
if(i < column){
result[0][i] = result[0][i - 1] + grid[0][i];
}
}
for(i = 1; i < row; i++){
for(int j = 1; j < column; j++){
result[i][j] = grid[i][j] + (result[i][j - 1] > result[i - 1][j] ? result[i - 1][j] : result[i][j - 1]);
}
}
return result[row - 1][column - 1];
}