Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +
, -
, and *
.
Example 1:
Input: "2-1-1"
Output: [0, 2]
Explanation: ((2-1)-1) = 0
(2-(1-1)) = 2
Example 2:
Input: "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
+
, -
, *
).def diffWaysToCompute(expression):
def compute(left, right, op):
results = []
for l in left:
for r in right:
if op == '+':
results.append(l + r)
elif op == '-':
results.append(l - r)
elif op == '*':
results.append(l * r)
return results
if expression.isdigit():
return [int(expression)]
results = []
for i, ch in enumerate(expression):
if ch in "+-*":
left = diffWaysToCompute(expression[:i])
right = diffWaysToCompute(expression[i+1:])
results.extend(compute(left, right, ch))
return results
# Example usages
print(diffWaysToCompute("2-1-1")) # Output: [0, 2]
print(diffWaysToCompute("2*3-4*5")) # Output: [-34, -14, -10, -10, 10]
m
. Each operation splits the problem into sub-problems.Thus, while the exact number of operations is hard to pinpoint, it grows exponentially with the length of the input expression due to the nature of recursive splitting.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?