【题目】
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.
【思路】
还是动态规划,可以直接用grid进行记录。
对于某一个格子,无非就是从左边走来或者从右边走来,那么这某个格子的新值就是左边和上边其中比较小的那个加上当前这个格子的值。
几个临界情况:
第一排,i = 0, j = 0, 第一个格子,就是gird[i][j] , 第一排其余格子,都是前一个格子的值累加自己格子的值。grid[i][j]+= grid[i -1][j]
对于最左边一列,只可能从上面那个格子集成,所以,grid[i][0]+= grid[i-1][0];
【代码】
public int minPathSum(int[][] grid) {
int m = grid.length;// row
int n = grid[0].length; // column
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 && j != 0) { //first line
grid[i][j] = grid[i][j] + grid[i][j - 1];
} else if (i != 0 && j == 0) { // left line
grid[i][j] = grid[i][j] + grid[i - 1][j];
} else if (i == 0 && j == 0) { // first grid
grid[i][j] = grid[i][j];
} else { // others
grid[i][j] = Math.min(grid[i][j - 1], grid[i - 1][j])
+ grid[i][j];
}
}
}
return grid[m - 1][n - 1];
}