64. Minimum path sum
Topic link
Source: LeetCode
Link: https://leetcode-cn.com/problems/minimum-path-sum/
Title description
Given an mxn grid containing non-negative integers, please find a path from the upper left corner to the lower right corner so that the sum of the numbers on the path is the smallest.
Note: You can only move one step down or right at a time.
Example 1:
Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Because the total of the path 1→3→1→1→1 is the smallest.
Example 2:
Input: grid = [[1,2,3],[4,5,6]]
Output: 12
prompt:
m == grid.length
n == grid[i].length
1 <= m, n <= 200
0 <= grid[i][j] <= 100
Topic analysis
top down.
The main issue is the handling of borders. Process the values in the first column and the first row.
And this problem does not need to create a new vector, the data can be processed in the original vector.
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
//处理边界
for(int i = 1; i < m; i++){
grid[i][0] = grid[i-1][0] + grid[i][0];
}
for(int j = 1; j < n; j++){
grid[0][j] = grid[0][j-1] + grid[0][j];
}
for(int i=1;i<m;i++){
for(int j=1;j<n;j++){
grid[i][j] = min(grid[i-1][j],grid[i][j-1]) + grid[i][j];
}
}
return grid[m-1][n-1];
}
};