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.
Example:
Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
对于本题,从原点到达(i, j)的最小路径等于 :原点到达(i-1, j)最小路径与到达(i, j-1)最小路径中的最小值。即 dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1]
采用动态规划。动态规划要求利用到上一次的结果,是一种特殊的迭代思想,动态规划的关键是要得到递推关系式。
class Solution {
public int minPathSum(int[][] grid) {
for(int i =1;i<grid.length;i++){ //给第一行都赋值
grid[i][0] += grid[i-1][0];
}
for(int j =1;j<grid[0].length;j++){//第一列都赋值
grid[0][j] +=grid[0][j-1];
}
for(int i =1;i<grid.length;i++){
for(int j =1;j<grid[0].length;j++){// 每个点的值为 他的左或上的最小值+当前值
grid[i][j] = Math.min( grid[i][j-1], grid[i-1][j])+ grid[i][j];
}
}
return grid[grid.length-1][grid[0].length-1];
}
}