Problem
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 1 0 4 10^4 104.
Algorithm
Use the backtracking method to calculate all possible cases.
Code
class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
nums, opts, val = [], [], 0
for c in expression:
if c >= '0' and c <= '9':
val = val * 10 + ord(c) - ord('0')
else:
opts.append(c)
nums.append(val)
val = 0
nums.append(val)
def dfs(L, R):
if L >= R:
return [nums[R]]
ans = []
for i in range(L, R):
val_L = dfs(L, i)
val_R = dfs(i+1, R)
for vl in val_L:
for vr in val_R:
if opts[i] == '+':
ans.append(vl + vr)
elif opts[i] == '-':
ans.append(vl - vr)
elif opts[i] == '*':
ans.append(vl * vr)
return ans
return dfs(0, len(opts))