LeetCode第64题:最小路径和(中等)
- 题目:给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。说明:每次只能向下或者向右移动一步。
- 思路一:又想到了第62题失败的那个方法,改进之后还是有些例子过不去。
class Solution {
public int minPathSum(int[][] grid) {
if(grid == null) return 0;
int R = grid.length - 1;
int D = grid[0].length - 1;
int ans=grid[R][D];
List<Integer> ans1 = new ArrayList<Integer>();
Path(R,D,ans,ans1,grid);
ans=Collections.min(ans1);
return ans;
}
public List<Integer> Path(int R,int D,int s,List<Integer> ans1,int[][] grid){
if(R==0 && D==0){
ans1.add(s);
s=grid[R][D];
return ans1;
}
if(R>0){
Path(R-1,D,s+grid[R-1][D],ans1,grid);
}
if(D>0){
Path(R,D-1,s+grid[R][D-1],ans1,grid);
}
return ans1;
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200213151235448.png)
- 思路二:利用递推公式grid(i,j)=grid(i,j)+min(dp(i+1,j),dp(i,j+1))
public class Solution {
public int minPathSum(int[][] grid) {
for (int i = grid.length - 1; i >= 0; i--) {
for (int j = grid[0].length - 1; j >= 0; j--) {
if(i == grid.length - 1 && j != grid[0].length - 1)
grid[i][j] = grid[i][j] + grid[i][j + 1];
else if(j == grid[0].length - 1 && i != grid.length - 1)
grid[i][j] = grid[i][j] + grid[i + 1][j];
else if(j != grid[0].length - 1 && i != grid.length - 1)
grid[i][j] = grid[i][j] + Math.min(grid[i + 1][j],grid[i][j + 1]);
}
}
return grid[0][0];
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/minimum-path-sum/solution/zui-xiao-lu-jing-he-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200213152228957.png)