Leetcode 241. Different Ways to Add Parentheses

[复制链接]
发表于 2025-11-7 21:55:48 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
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
  1. class Solution:
  2.     def diffWaysToCompute(self, expression: str) -> List[int]:
  3.         nums, opts, val = [], [], 0
  4.         for c in expression:
  5.             if c >= '0' and c <= '9':
  6.                 val = val * 10 + ord(c) - ord('0')
  7.             else:
  8.                 opts.append(c)
  9.                 nums.append(val)
  10.                 val = 0
  11.         nums.append(val)
  12.         def dfs(L, R):
  13.             if L >= R:
  14.                 return [nums[R]]
  15.             ans = []
  16.             for i in range(L, R):
  17.                 val_L = dfs(L, i)
  18.                 val_R = dfs(i+1, R)
  19.                 for vl in val_L:
  20.                     for vr in val_R:
  21.                         if opts[i] == '+':
  22.                             ans.append(vl + vr)
  23.                         elif opts[i] == '-':
  24.                             ans.append(vl - vr)
  25.                         elif opts[i] == '*':
  26.                             ans.append(vl * vr)
  27.             return ans
  28.         return dfs(0, len(opts))
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
继续阅读请点击广告
回复

使用道具 举报

×
登录参与点评抽奖,加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表