当前位置:网站首页>leetcode-241:为运算表达式设计优先级
leetcode-241:为运算表达式设计优先级
2022-07-02 23:55:00 【菊头蝙蝠】
leetcode-241:为运算表达式设计优先级
题目
给你一个由数字和运算符组成的字符串 expression ,按不同优先级组合数字和运算符,计算并返回所有可能组合的结果。你可以 按任意顺序 返回答案。
生成的测试用例满足其对应输出值符合 32 位整数范围,不同结果的数量不超过 104 。
示例 1:
输入:expression = "2-1-1"
输出:[0,2]
解释:
((2-1)-1) = 0
(2-(1-1)) = 2
示例 2:
输入:expression = "2*3-4*5"
输出:[-34,-14,-10,-10,10]
解释:
(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
解题
方法一:dfs(分治)
class Solution {
public:
vector<int> diffWaysToCompute(string expression) {
return dfs(0,expression.size()-1,expression);
}
vector<int> dfs(int l,int r,string& s){
vector<int> res;
for(int i=l;i<=r;i++){
if(s[i]>='0'&&s[i]<='9') continue;
vector<int> l1=dfs(l,i-1,s);//分治:获得运算符左侧结果
vector<int> l2=dfs(i+1,r,s);//分治:获得运算符右侧结果
for(int a:l1){
for(int b:l2){
int cur=0;
if(s[i]=='+') cur=a+b;
else if(s[i]=='-') cur=a-b;
else cur=a*b;
res.push_back(cur);
}
}
}
if(res.empty()){
int num=0;
for(int i=l;i<=r;i++){
num=num*10+s[i]-'0';
}
res.push_back(num);
}
return res;
}
};
边栏推荐
- Multiprocess programming (II): Pipeline
- node_ Modules cannot be deleted
- pod生命周期详解
- Multi process programming (III): message queue
- Rust所有权(非常重要)
- Centos7 one click compilation to build MySQL script
- About the practice topic of screen related to unity screen, unity moves around a certain point inside
- Shell implements basic file operations (SED edit, awk match)
- 【雅思阅读】王希伟阅读P1(阅读判断题)
- 【雅思阅读】王希伟阅读P2(阅读填空)
猜你喜欢
字符设备注册常用的两种方法和步骤
1.12 - 指令
Use Jenkins II job
UART、RS232、RS485、I2C和SPI的介绍
Hdu3507 (slope DP entry)
文件操作IO-Part2
Vulkan performance and refinement
【AutoSAR 十三 NVM】
Baidu AI Cloud takes the lead in building a comprehensive and standardized platform for smart cloud
Explain in detail the significance of the contour topology matrix obtained by using the contour detection function findcontours() of OpenCV, and how to draw the contour topology map with the contour t
随机推荐
图解网络:什么是虚拟路由器冗余协议 VRRP?
Free we media essential tools sharing
Introduction and use of ftrace tool
1.12 - Instructions
Andorid gets the system title bar height
【小程序项目开发-- 京东商城】uni-app之自定义搜索组件(中)-- 搜索建议
多进程编程(四):共享内存
Extension of flutter
Is there a free text to speech tool to help recommend?
Graduation summary
2022 list of manufacturers of Chinese 3D vision enterprises (guided positioning and sorting scenes)
Centos7 one click compilation to build MySQL script
如何系统学习机器学习
Basic use of shell script
【AutoSAR 五 方法论】
2022中国3D视觉企业(引导定位、分拣场景)厂商名单
Explain in detail the significance of the contour topology matrix obtained by using the contour detection function findcontours() of OpenCV, and how to draw the contour topology map with the contour t
University of Toronto: Anthony coach | the conditions of deep reinforcement learning can induce dynamic risk measurement
Hundreds of continuous innovation to create free low code office tools
Pageoffice - bug modification journey