解决思路
二维动态规划
public int minPathSum(int[][] grid) {
int R = grid.length;
int C = grid[0].length;
int[][] dp = new int[R][C];
for (int i = R - 1;i >= 0;i--){
for (int j = C - 1;j >= 0;j--){
if (i == R - 1 && j == C - 1)
dp[i][j] = grid[i][j];
else if (i == R - 1 && j != C - 1)
dp[i][j] = dp[i][j + 1] + grid[i][j];
else if (j == C - 1 && i != R - 1)
dp[i][j] = dp[i + 1][j] + grid[i][j];
else
dp[i][j] = Math.min(dp[i + 1][j],dp[i][j + 1]) + grid[i][j];
}
}
return dp[0][0];
}
一维动态规划
public int minPathSum(int[][] grid) {
int[] dp = new int[grid[0].length];
for (int i = grid.length - 1; i >= 0; i--) {
for (int j = grid[0].length - 1; j >= 0; j--) {
if(i == grid.length - 1 && j != grid[0].length - 1)
dp[j] = grid[i][j] + dp[j + 1];
else if(j == grid[0].length - 1 && i != grid.length - 1)
dp[j] = grid[i][j] + dp[j];
else if(j != grid[0].length - 1 && i != grid.length - 1)
dp[j] = grid[i][j] + Math.min(dp[j], dp[j + 1]);
else
dp[j] = grid[i][j];
}
}
return dp[0];
}
动态规划(不需要额外存储空间)
public int minPathSum(int[][] grid) {
for (int i = grid.length - 1; i >= 0; i--) {
for (int j = grid[0].length - 1; j >= 0; j--) {
if(i == grid.length - 1 && j != grid[0].length - 1)
grid[i][j] = grid[i][j] + grid[i][j + 1];
else if(j == grid[0].length - 1 && i != grid.length - 1)
grid[i][j] = grid[i][j] + grid[i + 1][j];
else if(j != grid[0].length - 1 && i != grid.length - 1)
grid[i][j] = grid[i][j] + Math.min(grid[i + 1][j],grid[i][j + 1]);
}
}
return grid[0][0];
}