# leecode64. 最小路径和(动态规划)

## 64. 最小路径和

class Solution {
public int minPathSum(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int[][] dp = new int[grid.length][grid[0].length];
for(int i = 0 ; i< grid.length ; i++){
for(int j=0;j<grid[i].length;j++){
if(i==0){
if(j==0){
dp[i][j] = grid[i][j];
}else{
dp[i][j] = grid[i][j]+dp[i][j-1];
}
}else if(j==0){
if(i==0){
dp[i][j] = grid[i][j];
}else{
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[grid.length-1][grid[0].length-1];
}
}


class Solution {
public int minPathSum(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
for(int i=1;i<grid.length;i++){
grid[i][0] += grid[i-1][0];
}
for(int i=1;i<grid[0].length;i++){
grid[0][i] +=grid[0][i-1];
}
for(int i = 1 ; i< grid.length ; i++){
for(int j=1;j<grid[i].length;j++){
grid[i][j] += Math.min(grid[i-1][j],grid[i][j-1]);
}
}
return grid[grid.length-1][grid[0].length-1];
}
}

posted @ 2022-07-20 10:35  zqy123  阅读(11)  评论(0编辑  收藏  举报