-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path931.下降路径最小和.js
58 lines (51 loc) · 1.19 KB
/
931.下降路径最小和.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
* @lc app=leetcode.cn id=931 lang=javascript
*
* [931] 下降路径最小和
*/
// @lc code=start
/**
* @param {number[][]} matrix
* @return {number}
*/
// const { createPrinter } = require('./utils/index')
// const printer = createPrinter()
var minFallingPathSum = function(matrix) {
let n = matrix.length
let res = Infinity
const memo = new Map()
for (let j = 0; j < matrix[0].length; j++) {
res = Math.min(res, dp(matrix, n - 1, j))
}
return res
function dp(matrix, i, j) {
// printer.logEnter(`i=${i}, j=${j}`)
if (i < 0 || j < 0 || i >= matrix.length || j >= matrix[0].length) {
// printer.logReturn(9999)
return 9999
}
if (i === 0) {
// printer.logReturn(matrix[i][j])
return matrix[i][j]
}
const key = `${i}-${j}`
if (memo.has(key)) {
return memo.get(key)
}
let res =
matrix[i][j] +
min(
dp(matrix, i - 1, j - 1),
dp(matrix, i - 1, j),
dp(matrix, i - 1, j + 1)
)
memo.set(key, res)
// printer.logReturn(res)
return res
}
function min(a, b, c) {
return Math.min(a, Math.min(b, c))
}
}
// @lc code=end
module.exports = { minFallingPathSum }