当前位置:网站首页>leetcode:241. 为运算表达式设计优先级【dfs + eval】
leetcode:241. 为运算表达式设计优先级【dfs + eval】
2022-07-01 12:35:00 【白速龙王的回眸】

分析
每次选择其中的a ? b进行加一对括号
知道用完所有运算符
然后放入一个set中防止运算式子相等即可
ac code
class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
ans = []
operators = ('+', '-', '*')
def countOperator(s):
cnt = 0
for c in s:
if c in operators:
cnt += 1
return cnt
s = set()
def dfs(nums, ops):
if len(nums) == 1:
s.add(nums[0])
return
# 选一个进行计算
for i in range(len(nums) - 1):
new_num = '(' + nums[i] + ops[i] + nums[i + 1] + ')'
new_nums = nums[:i] + [new_num] + nums[i + 2:]
new_ops = ops[:i] + ops[i + 1:]
dfs(new_nums, new_ops)
# pattern要按ascii码
nums = re.split('[*+-]', expression)
ops = []
for c in expression:
if c in operators:
ops.append(c)
dfs(nums, ops)
return [eval(exp) for exp in s]
总结
dfs来选可以选的地方
re.split来区分符号和数字,主要要根据ascii码的顺序
然后最后通过eval计算所有不同式子的结果即可
边栏推荐
- [some notes]
- Onenet Internet of things platform - mqtt product devices send messages to message queues MQ
- Perl 5.10.0 installation package download
- How to install php7 and perform performance test using yum
- IOS interview
- Need your own cognition
- 华为面试题: 招聘
- Blue Bridge Cup multi interface switching processing (enumeration plus state machine method)
- 腾讯安全联合毕马威发布监管科技白皮书,解析“3+3”热点应用场景
- 《MATLAB 神经网络43个案例分析》:第40章 动态神经网络时间序列预测研究——基于MATLAB的NARX实现
猜你喜欢
![[106] 360 check font - check whether the copyright of local Fonts is commercially available](/img/a7/615e8000647b56f03a6a1d3dd81b6d.jpg)
[106] 360 check font - check whether the copyright of local Fonts is commercially available

redis探索之缓存击穿、缓存雪崩、缓存穿透

Typora realizes automatic uploading of picture pasting

Chained storage of queues

晓看天色暮看云,美图欣赏

Indefinite integral

How to use opcache, an optimization acceleration component of PHP
![[datawhale202206] pytorch recommendation system: multi task learning esmm & MMOE](/img/8f/64fea641730795a2b5252cc2c8cdd2.png)
[datawhale202206] pytorch recommendation system: multi task learning esmm & MMOE

【20211129】Jupyter Notebook远程服务器配置
![[JS] interview questions](/img/f3/8cf430b999980190a250f89537715e.jpg)
[JS] interview questions
随机推荐
VS Code 设置代码自动保存
Typora realizes automatic uploading of picture pasting
Share several tools for designing exquisite circuit diagrams
Blocking sockets的读写操作该怎么玩?
fatal error: execution: 没有那个文件或目录
CPI tutorial - asynchronous interface creation and use
MySQL common functions
硬阈值(Hard Thresholding)函数解读[通俗易懂]
Leetcode (Sword finger offer) - 58 - ii Rotate string left
Tencent Li Wei: deeply cultivate "regulatory technology" to escort the steady and long-term development of the digital economy
队列的链式存储
Operations related to sequence table
System test UI test summary and questions (interview)
MySQL data table creation
【datawhale202206】pyTorch推荐系统:多任务学习 ESMM&MMOE
编译调试Net6源码
【20211129】Jupyter Notebook远程服务器配置
(混更一篇)多个txt文本转一个表格
[datawhale202206] pytorch recommendation system: precision model deepfm & DIN
下半年还有很多事要做