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.
解析1:使用动态规划,对于最上一排点(m,n)的最短路径长度f(m,n)永远等于f(m,n-1) + grid(m,n);对于最左边一列点,f(m,n)=f(m-1,n) + grid(m,n);对于其它点,永远f(m,n)=min(f(m-1,n),f(m,n-1))+grid(m,n),时间复杂度o(mn),代码如下:
class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[][] res = new int[m][n];
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[i].length;j++){
if(i==0 && j ==0){
res[i][j] = grid[i][j];
continue;
}
if(i == 0){
res[i][j] = res[i][j-1] + grid[i][j];
continue;
}
if(j == 0){
res[i][j] = res[i-1][j] + grid[i][j];
continue;
}
res[i][j] = Math.min(res[i-1][j], res[i][j-1]) + grid[i][j];
}
}
return res[m-1][n-1];
}
}