-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathDifferent Ways to Add Parentheses.js
54 lines (43 loc) · 1.9 KB
/
Different Ways to Add Parentheses.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
var diffWaysToCompute = function(expression) {
// We can iterate through the expression character-by-character.
// we can break the expression into two halves whenever we get an operator (+, -, *).
// The two parts can be calculated by recursively calling the function.
// Once we have the evaluation results from the left and right halves, we can combine them to produce all results.
return diffWaysRec({},expression)
};
function diffWaysRec(map, expression){
if(expression in map){
return map[expression]
}
let result = [];
if(!(expression.includes("+")) && !(expression.includes("-")) && !(expression.includes("*"))){
result.push(parseInt(expression))
}else {
for(let i =0; i<expression.length; i++){
let char = expression[i];
if(isNaN(parseInt(char,10))){
//not a number , must it expression
//calculate lest and right now
let leftParts = diffWaysRec(map,expression.substring(0,i));
let rightParts = diffWaysRec(map, expression.substring(i+1));
for(let l = 0; l<leftParts.length; l++){
for(let r = 0; r<rightParts.length; r++){
let left = leftParts[l];
let right = rightParts[r];
if(char === "+"){
result.push(parseInt(left) + parseInt(right))
}
if(char === "-"){
result.push(parseInt(left) - parseInt(right))
}
if(char === "*"){
result.push(parseInt(left) * parseInt(right))
}
}
}
}
}
}
map[expression] = result;
return result;
}