题目
给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。
说明:每次只能向下或者向右移动一步。
示例:
输入:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
输出: 7
解释: 因为路径 1→3→1→1→1 的总和最小。
思路
思路
- 状态定义:
设dp[i][j]为走到当前位置的最小路径和
- 递推公式:
只能向下或向右走,意味着当前格子只能由上边或者左边走过来
dp[i][j] = Min(dp[i-1][j],dp[i][j-1]) + grid[i][j]
- 初始化
第一行第n列和第一列第n行为均原数组值
- 边界条件
格子有边界,因此当i==0 或j==0时,i-1和j-1会越界
i = 0,j != 0时,dp[i][j] = dp[i][j-1]+grid[i][j]
i !=0,j == 0时,dp[i][j] = dp[i-1][j]+grid[i][j]
i !=0 && j != 0时,dp[i][j] = Min(dp[i-1][j],dp[i][j-1])+grid[i][j]
i == 0 && j == 0时,dp[i][j]=grid[i][j]
- 返回值
dp最后一个元素值
代码
cpp代码
#include <stdio.h>
#include <vector>
class Solution {
public:
int minPathSum(std::vector<std::vector<int> >& grid) {
if (grid.size() == 0){
return 0;
}
int row = grid.size();
int column = grid[0].size();
std::vector<std::vector<int> >
dp(row, std::vector<int>(column, 0));
dp[0][0] = grid[0][0];
for (int i = 1; i < column; i++){
dp[0][i] = dp[0][i-1] + grid[0][i];
}
for (int i = 1; i < row; i++){
dp[i][0] = dp[i-1][0] + grid[i][0];
for (int j = 1; j < column; j++){
dp[i][j] = std::min(dp[i-1][j], dp[i][j-1]) + grid[i][j];
}
}
return dp[row-1][column-1];
}
};
int main(){
int test[][3] = {{1,3,1}, {1,5,1}, {4,2,1}};
std::vector<std::vector<int> > grid;
for (int i = 0; i < 3; i++){
grid.push_back(std::vector<int>());
for (int j = 0; j < 3; j++){
grid[i].push_back(test[i][j]);
}
}
Solution solve;
printf("%d\n", solve.minPathSum(grid));
return 0;
}
java代码
package minimum_path_sum;
//64.最小路径和
public class Solution {
public int minPathSum(int[][] grid) {
//定义dp数组
int[][] dp = new int[grid.length][grid[0].length];
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)//如果右边界,那么只能向左走
dp[i][j] = grid[i][j] + dp[i][j + 1];
else if(j == grid[0].length - 1 && i != grid.length - 1)//如果下边界,那么只能向上走
dp[i][j] = grid[i][j] + dp[i + 1][j];
else if(j != grid[0].length - 1 && i != grid.length - 1)//如果不是边界的情况,则要进行判断最小路径和
dp[i][j] = grid[i][j] + Math.min(dp[i + 1][j], dp[i][j + 1]);
else
dp[i][j] = grid[i][j];//从这个元素开始走
}
}
return dp[0][0];
}
public static void main(String[] args) {
int[][] grid = {{1,3,1},{1,5,1},{4,2,1}};
Solution solu = new Solution();
System.out.println(solu.minPathSum(grid));
}
}