Skip to content

Commit 0749af8

Browse files
authored
Update 1981-minimize-the-difference-between-target-and-chosen-elements.js
1 parent e78a83d commit 0749af8

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

1981-minimize-the-difference-between-target-and-chosen-elements.js

+26
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,29 @@ const minimizeTheDifference = function(mat, target) {
1919
}
2020
};
2121

22+
// another
23+
24+
/**
25+
* @param {number[][]} mat
26+
* @param {number} target
27+
* @return {number}
28+
*/
29+
const minimizeTheDifference = function(mat, target) {
30+
const m = mat.length, n = mat[0].length
31+
const memo = Array.from({ length: m }, () => Array())
32+
return dfs(0, 0)
33+
34+
function dfs(row, sum) {
35+
if(row === m) return Math.abs(target - sum)
36+
if(memo[row][sum] != null) return memo[row][sum]
37+
let res = Number.MAX_SAFE_INTEGER
38+
for(let i = 0; i < n; i++) {
39+
res = Math.min(res, dfs(row + 1, sum + mat[row][i]))
40+
}
41+
42+
return memo[row][sum] = res
43+
}
44+
};
45+
46+
47+

0 commit comments

Comments
 (0)