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.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-path-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
1. 思路和前面62. 63差不多
2. dp[i][j]表示在位置 i , j 处的最小和
位于起点即 i == 0 && j == 0 时,dp[i][j]等于起点处的值
当位于第一排时,只能由其左边的值决定,位于第一列时,由其上面的值决定
其他位置处 dp[i][j] = min(左边dp+此处的值,上面dp+此处的值)
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
if(m == 0 || n == 0)
return 0;
int dp[m][n] = {0};
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(i == 0 && j == 0) dp[i][j] = grid[i][j];
else if(i == 0) dp[i][j] = dp[i][j-1] + grid[i][j];
else if(j == 0) dp[i][j] = dp[i-1][j] + grid[i][j];
else{
dp[i][j] = min(dp[i-1][j]+grid[i][j], dp[i][j-1]+grid[i][j]);
}
}
}
return dp[m-1][n-1];
}
};