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.
二维DP。设数组A[row][col],
Min[i][j] = min(Min[i-1][j], Min[i][j-1]) +A[i][j];
注意初始条件即可。
public class Solution { public int minPathSum(int[][] grid) { int m = grid.length; int n = grid[0].length; int[][] sum = new int[m+2][n+2]; for(int i = 0; i < m + 2; i++){ for(int j = 0; j < n + 2; j++){ sum[i][j] = Integer.MAX_VALUE; } } sum[m][n+1] = 0; for(int i = m; i >= 1; i--){ for(int j = n; j >= 1; j--){ sum[i][j] = grid[i-1][j-1] + Math.min(sum[i+1][j], sum[i][j+1]); } } return sum[1][1]; } }
没必要用二维数组,用滚动数组即可。(TODO) 看水中的鱼
1 public class Solution { 2 public int minPathSum(int[][] grid) { 3 int row = grid.length; 4 int col = grid[0].length; 5 int[] steps = new int[col]; 6 for(int i = 0; i< col; i++){ 7 steps[i] = Integer.MAX_VALUE; 8 } 9 steps[0] = 0; 10 for(int i = 0; i < row; i++){ 11 steps[0] = steps[0] + grid[i][0]; 12 for(int j = 1; j< col; j++){ 13 steps[j] = Math.min(steps[j-1], steps[j])+grid[i][j]; 14 } 15 } 16 return steps[col -1]; 17 } 18 }