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.
还是这道题的变形:
上次在每个格子里放01 这次放正整数
之前dp[i][j] 表示路径的数目 采用dp[i+1][j]+dp[i][j+1]
这个dp[i][j]表示路径长度 所以要采用 max(dp[i+1][j] ,dp[i][j+1] ) +grid[i][j]
public int minPathSum(int[][] grid) {
int m = grid.length;
if(m == 0) return 0;
int n = grid[0].length;
int[][] dp = new int[m][n];
int i,j;
for(int index = m*n-1;index >= 0;index--){
i = index / n;
j = index % n;
if(index == m*n-1) dp[i][j] = grid[i][j];
else{
dp[i][j] = grid[i][j];
if(i+1 >= m) dp[i][j] += dp[i][j+1];
else if(j+1 >= n) dp[i][j] += dp[i+1][j] ;
else{
dp[i][j] += Integer.min(dp[i+1][j], dp[i][j+1]);
}
}
}
// for(i = 0;i < m;i++){
// for(j = 0;j < n;j++)
// System.out.printf("%4d",dp[i][j]);
// System.out.println();
// }
return dp[0][0];
}