最小路径和
给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。
说明:每次只能向下或者向右移动一步。
示例:
输入:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
输出: 7
解释: 因为路径 1→3→1→1→1 的总和最小。
动态规划
1 当左边和上边都不是矩阵的边界时,
i !=0 ,j !=0; dp[i][j] = min(dp[i-1][j],dp[i][j-1]) +grid[i][j];
2当只有左边是矩阵的边界时,只能从上面来,
i =0 ,j !=0; dp[i][j] =dp[i][j-1] +grid[i][j];
3当只有上边是矩阵的边界时,只能从左边来,
i !=0 ,j =0; dp[i][j] =dp[i-1][j] +grid[i][j];
4当左边和上边是矩阵的边界时,
i =0 ,j =0;其实就是起点 dp[i][j]=grid[i][j];
public int minPathSum(int[][] grid) {
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[0].length; j++) {
if(i == 0 && j == 0) continue;
else if(i == 0) grid[i][j] = grid[i][j - 1] + grid[i][j];
else if(j == 0) grid[i][j] = grid[i - 1][j] + grid[i][j];
else grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]);
}
}
return grid[grid.length - 1][grid[0].length - 1];
}
不改变原数组的情况下
public class Test9 {
public static void main(String[] args) {
int[][] grid ={{1,3,1},{1,5,1},{4,2,1}};
System.out.println(minPathSum(grid));
}
public static int minPathSum(int[][] grid) {
if(grid == null){
return 0;
}
int m = grid.length;
int n = grid[0].length;
int[][] dp = new int[m][n];
for(int i =0;i<m;i++){
for(int j =0;j<n;j++){
if(i == 0 && j == 0) {
dp[i][j]=grid[i][j];
}else if(i == 0){
dp[i][j] = grid[i][j]+dp[i][j-1];
}else if(j == 0){
dp[i][j] = grid[i][j]+dp[i-1][j];
}else{
dp[i][j] = grid[i][j]+Math.min(dp[i-1][j],dp[i][j-1]);
}
}
}
return dp[m-1][n-1];
}
}