Different Ways to Add Parentheses LeetCode solution in JavaScript

1
var diffWaysToCompute = function (expression) {
2
// We can iterate through the expression character-by-character.
3
// we can break the expression into two halves whenever we get an operator (+, -, *).
4
// The two parts can be calculated by recursively calling the function.
5
// Once we have the evaluation results from the left and right halves, we can combine them to produce all results.
6

7
return diffWaysRec({}, expression);
8
};
9

10
function diffWaysRec(map, expression) {
11
if (expression in map) {
12
return map[expression];
13
}
14
let result = [];
15

16
if (
17
!expression.includes("+") &&
18
!expression.includes("-") &&
19
!expression.includes("*")
20
) {
21
result.push(parseInt(expression));
22
} else {
23
for (let i = 0; i < expression.length; i++) {
24
let char = expression[i];
25

26
if (isNaN(parseInt(char, 10))) {
27
//not a number , must it expression
28
//calculate lest and right now
29
let leftParts = diffWaysRec(map, expression.substring(0, i));
30
let rightParts = diffWaysRec(map, expression.substring(i + 1));
31
for (let l = 0; l < leftParts.length; l++) {
32
for (let r = 0; r < rightParts.length; r++) {
33
let left = leftParts[l];
34
let right = rightParts[r];
35

36
if (char === "+") {
37
result.push(parseInt(left) + parseInt(right));
38
}
39
if (char === "-") {
40
result.push(parseInt(left) - parseInt(right));
41
}
42
if (char === "*") {
43
result.push(parseInt(left) * parseInt(right));
44
}
45
}
46
}
47
}
48
}
49
}
50

51
map[expression] = result;
52
return result;
53
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0