241. Different Ways to Add Parentheses
Description
Given a string expression
of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. You may return the answer in any order.
The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed 104
.
Example 1:
Input: expression = "2-1-1" Output: [0,2] Explanation: ((2-1)-1) = 0 (2-(1-1)) = 2
Example 2:
Input: expression = "2*3-4*5" Output: [-34,-14,-10,-10,10] Explanation: (2*(3-(4*5))) = -34 ((2*3)-(4*5)) = -14 ((2*(3-4))*5) = -10 (2*((3-4)*5)) = -10 (((2*3)-4)*5) = 10
Constraints:
1 <= expression.length <= 20
expression
consists of digits and the operator'+'
,'-'
, and'*'
.- All the integer values in the input expression are in the range
[0, 99]
.
Solutions
Solution: Recursion + Memoization
- Time complexity: O(2n)
- Space complexity: O(n*2n)
JavaScript
js
/**
* @param {string} expression
* @return {number[]}
*/
const diffWaysToCompute = function (expression) {
const memo = new Map();
const calculate = (a, b, mathSymbol) => {
if (mathSymbol === '*') return a * b;
if (mathSymbol === '-') return a - b;
return a + b;
};
const computeExpression = current => {
if (memo.has(current)) return memo.get(current);
const n = current.length;
const values = [];
for (let index = 0; index < n; index++) {
const str = current[index];
if (/\d/.test(str)) continue;
const leftHalf = current.slice(0, index);
const rightHalf = current.slice(index + 1);
const values1 = computeExpression(leftHalf);
const values2 = computeExpression(rightHalf);
for (const value1 of values1) {
for (const value2 of values2) {
const value = calculate(value1, value2, str);
values.push(value);
}
}
}
const result = values.length ? values : [+current];
memo.set(current, result);
return result;
};
return computeExpression(expression);
};