马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
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 10410^4104.
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))
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
|