版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/GYH0730/article/details/84838446
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.
Example:
Input: [ [1,3,1], [1,5,1], [4,2,1] ] Output: 7 Explanation: Because the path 1→3→1→1→1 minimizes the sum.
dp入门题,dp[i][j] = a[i][j] + min(dp[i+1][j],dp[i][j+1]),注意边界处理。
class Solution {
public int minPathSum(int[][] grid) {
int n,m;
n = grid.length;
m = grid[0].length;
int dp[][] = new int[n][m];
for(int i = n - 1; i >= 0; i--) {
for(int j = m - 1; j >= 0; j--) {
if(i == n - 1 && j == m - 1) dp[i][j] = grid[i][j];
else if(i == n - 1) dp[i][j] = grid[i][j] + dp[i][j + 1];
else if(j == m - 1) 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[0][0];
}
}