image.png

解决思路

二维动态规划

image.png

  1. public int minPathSum(int[][] grid) {
  2. int R = grid.length;
  3. int C = grid[0].length;
  4. int[][] dp = new int[R][C];
  5. for (int i = R - 1;i >= 0;i--){
  6. for (int j = C - 1;j >= 0;j--){
  7. if (i == R - 1 && j == C - 1)
  8. dp[i][j] = grid[i][j];
  9. else if (i == R - 1 && j != C - 1)
  10. dp[i][j] = dp[i][j + 1] + grid[i][j];
  11. else if (j == C - 1 && i != R - 1)
  12. dp[i][j] = dp[i + 1][j] + grid[i][j];
  13. else
  14. dp[i][j] = Math.min(dp[i + 1][j],dp[i][j + 1]) + grid[i][j];
  15. }
  16. }
  17. return dp[0][0];
  18. }

一维动态规划

image.png

  1. public int minPathSum(int[][] grid) {
  2. int[] dp = new int[grid[0].length];
  3. for (int i = grid.length - 1; i >= 0; i--) {
  4. for (int j = grid[0].length - 1; j >= 0; j--) {
  5. if(i == grid.length - 1 && j != grid[0].length - 1)
  6. dp[j] = grid[i][j] + dp[j + 1];
  7. else if(j == grid[0].length - 1 && i != grid.length - 1)
  8. dp[j] = grid[i][j] + dp[j];
  9. else if(j != grid[0].length - 1 && i != grid.length - 1)
  10. dp[j] = grid[i][j] + Math.min(dp[j], dp[j + 1]);
  11. else
  12. dp[j] = grid[i][j];
  13. }
  14. }
  15. return dp[0];
  16. }

动态规划(不需要额外存储空间)

image.png

  1. public int minPathSum(int[][] grid) {
  2. for (int i = grid.length - 1; i >= 0; i--) {
  3. for (int j = grid[0].length - 1; j >= 0; j--) {
  4. if(i == grid.length - 1 && j != grid[0].length - 1)
  5. grid[i][j] = grid[i][j] + grid[i][j + 1];
  6. else if(j == grid[0].length - 1 && i != grid.length - 1)
  7. grid[i][j] = grid[i][j] + grid[i + 1][j];
  8. else if(j != grid[0].length - 1 && i != grid.length - 1)
  9. grid[i][j] = grid[i][j] + Math.min(grid[i + 1][j],grid[i][j + 1]);
  10. }
  11. }
  12. return grid[0][0];
  13. }