题目描述
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.
解决思路
动态规划思想。
利用每格保存之前走过的最短路径,最后得到最末的值即为最短路径。
源码
class Solution {
public int minPathSum(int[][] grid) {
int column=grid[0].length;
int row=grid.length;
for(int i=0;i<row;i++){
for(int j=0;j<column;j++){
if(i==0&&j==0){
continue;
}else if(i==0&&j!=0){
grid[i][j]=grid[i][j]+grid[i][j-1];
}else if(i!=0&&j==0){
grid[i][j]=grid[i-1][j]+grid[i][j];
}else{
grid[i][j]=grid[i][j]+Math.min(grid[i-1][j],grid[i][j-1]);
}
}
}
return grid[row-1][column-1];
}
}
近期评论