-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.js
More file actions
46 lines (42 loc) · 1.16 KB
/
Copy pathsolution.js
File metadata and controls
46 lines (42 loc) · 1.16 KB
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
/**
* @param {string} s
* @param {number} target
* @returns {string[]}
*/
class Solution {
findExpr(s, target) {
const res = [];
if (!s || s.length === 0) return res;
const n = s.length;
function dfs(pos, expr, curVal, last) {
if (pos === n) {
if (curVal === target) res.push(expr);
return;
}
for (let i = pos; i < n; ++i) {
if (i > pos && s[pos] === "0") break; // skip leading zero numbers
const numStr = s.slice(pos, i + 1);
const val = Number(numStr);
if (pos === 0) {
// first number (no operator before)
dfs(i + 1, numStr, val, val);
} else {
// plus
dfs(i + 1, expr + "+" + numStr, curVal + val, val);
// minus
dfs(i + 1, expr + "-" + numStr, curVal - val, -val);
// multiply: replace last contribution with last * val
dfs(
i + 1,
expr + "*" + numStr,
curVal - last + last * val,
last * val
);
}
}
}
dfs(0, "", 0, 0);
res.sort(); // lexicographic order
return res;
}
}