-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path241. Different Ways to Add Parentheses.ts
48 lines (42 loc) · 1.13 KB
/
241. Different Ways to Add Parentheses.ts
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
/**
* Runtime 80 ms Beats 50%
* Memory 45.1 MB Beats 66.67%
*/
function diffWaysToCompute(expression: string): number[] {
const results: number[] = [];
if (
!(
expression.includes('+') ||
expression.includes('-') ||
expression.includes('*')
)
) {
results.push(+expression);
return results;
}
const sign = ['+', '-', '*'];
for (let i = 0; i < expression.length; i++) {
const currentExp = expression[i];
if (sign.includes(currentExp)) {
const leftExp = diffWaysToCompute(expression.substring(0, i));
const rightExp = diffWaysToCompute(expression.substring(i + 1));
for (const leftNum of leftExp) {
for (const rightNum of rightExp) {
switch (currentExp) {
case '+':
results.push(leftNum + rightNum);
break;
case '-':
results.push(leftNum - rightNum);
break;
case '*':
results.push(leftNum * rightNum);
break;
}
}
}
}
}
return results;
}
console.log(diffWaysToCompute('2*3-4*5')); // [ -34, -10, -14, -10, 10 ]