Expression Add Operators LeetCode solution in JavaScript

1
var addOperators = function (num, target) {
2
let res = [];
3

4
let i = 0;
5

6
const helper = (idx, sum, prev, path) => {
7
if (idx >= num.length) {
8
if (sum === target) {
9
res.push(path);
10
}
11
return null;
12
}
13

14
for (let j = idx; j < num.length; j++) {
15
if (j !== idx && num[idx] === "0") break;
16

17
let n = Number(num.slice(idx, j + 1));
18

19
if (idx === 0) {
20
helper(j + 1, sum + n, sum + n, path + n);
21
} else {
22
helper(j + 1, sum + n, n, path + "+" + n);
23

24
helper(j + 1, sum - n, 0 - n, path + "-" + n);
25

26
helper(j + 1, sum - prev + prev * n, prev * n, path + "*" + n);
27
}
28
}
29
};
30

31
helper(i, 0, 0, "");
32

33
return res;
34
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0