-
Notifications
You must be signed in to change notification settings - Fork 65
/
最小路径和.js
30 lines (28 loc) · 874 Bytes
/
最小路径和.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* @param {number[][]} grid
* @return {number}
* dp[i][j] = minSum?
* dp[i][j] = Math.min(dp[i-1][j] + grid[i][j], dp[i][j-1] + grid[i][j])
Infinity Infinity Infinity
Infinity[1, 4, 5]
Infinity[2, 7, 6]
Infinity[6, 8, 7]
*/
var minPathSum = function(grid) {
const row = grid.length;
const col = grid[0].length;
const dp = new Array(row).fill(0).map(_ => new Array(col).fill(0));
dp[0][0] = grid[0][0];
dp[-1] = new Array(col).fill(Infinity);
for (let i = 0; i < row; i++) {
dp[i][-1] = Infinity;
}
for (let i = 0; i < row; i++) {
for (let j = 0; j < col; j++) {
if (i === 0 && j === 0) continue;
dp[i][j] = Math.min(dp[i - 1][j] + grid[i][j], dp[i][j - 1] + grid[i][j]);
}
}
console.log(dp);
return dp[row - 1][col - 1];
};