64. Minimum Path Sum
Given a m x n
grid of non-negative integers grid
, find a path from the upper left corner to the lower right corner that minimizes the sum of numbers on the path.
Note: Only move down or right one step at a time.
Example 1:
输入:grid = [[1,3,1],[1,5,1],[4,2,1]]
输出:7
解释:因为路径 1→3→1→1→1 的总和最小。
Example 2:
输入:grid = [[1,2,3],[4,5,6]]
输出:12
hint:
m == grid.length
n == grid[i].length
1 <= m, n <= 200
0 <= grid[i][j] <= 100
problem solving ideas
dynamic programming
Learning ideas: After watching this video, you won’t feel that dynamic programming is difficult to learn, the minimum path sum, Leetcode64, lecturer version
-
Initialize the dp table
-
Calculate the minimum path sum of horizontal and vertical coordinates
-
Abscissa
-
Y-axis
-
-
Calculate the path sum in the remaining spaces
-
compare path and shortest
- likeGreen path and +grid current paththe smallest
- The orange area is the calculated value
- likered path and +grid current paththe smallest
- The orange area is the calculated value
- likeGreen path and +grid current paththe smallest
-
Iterate over the remainder of the inner
-
-
Finally, take
dp[rowLength-1] [colLength-1]
the minimum path
Code
var minPathSum = function(grid) {
let rowLength=grid.length;
let colLength=grid[0].length;
let dp=new Array(colLength);
for(let index=0;index<rowLength;index++){
dp[index]=new Array(colLength);
}
dp[0][0]=grid[0][0];
for(let index=1;index<colLength;index++){
dp[0][index]=dp[0][index-1]+grid[0][index];
}
for(let index=1;index<rowLength;index++){
dp[index][0]=dp[index-1][0]+grid[index][0];
}
for(let row=1;row<rowLength;row++){
for(let col=1;col<colLength;col++){
dp[row][col]=Math.min(dp[row-1][col],dp[row][col-1])+grid[row][col];
}
}
return dp[rowLength-1][colLength-1];
};