题目描述
一个 m x n 的矩阵填充着非负整数,找到从左上角到右下角和最小的路径。
注:每一步只能向下一格走或向右一格走。
递归例程:
public class Solution {
public int minPathSum(int[][] grid) {
if(grid == null||grid.length == 0||grid[0].length == 0)
return 0;
return help(grid,0,0);
}
public int help(int[][] grid,int row,int col)
{
if(row == grid.length-1&&col == grid[0].length-1)
return grid[row][col];//达到bottom right时返回该值
if(row == grid.length-1&&col!=grid[0].length-1)//到达最后一行的情况
return grid[row][col]+help(grid,row,col+1);
if(col == grid[0].length-1&&row!=grid.length-1)//到达最后一列的情况
return grid[row][col]+help(grid,row+1,col);
else//一般情况
{
int down=help(grid,row+1,col);
int right=help(grid,row,col+1);
if(down<right)
return down+grid[row][col];
else
return right+grid[row][col];
}
}
}
DP例程:
public class Solution {
public int minPathSum(int[][] grid) {
if(grid == null||grid.length == 0||grid[0].length == 0)
return 0;
int row=grid.length;
int col=grid[0].length;
int[][] dp=new int[row][col];
//第一个值初始化
dp[row-1][col-1]=grid[row-1][col-1];
//对最下行初始化
for(int j=col-2;j>=0;j--)
{
dp[row-1][j]=dp[row-1][j+1]+grid[row-1][j];
}
//对最右列初始化
for(int i=row-2;i>=0;i--)
{
dp[i][col-1]=dp[i+1][col-1]+grid[i][col-1];
}
//general
for(int i=row-2;i>=0;i--)
{
for(int j=col-2;j>=0;j--)
{
int down=dp[i+1][j];
int right=dp[i][j+1];
dp[i][j]=down<right?down+grid[i][j]:right+grid[i][j];
}
}
return dp[0][0];
}
}
.