当前位置:网站首页>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;
}
};
边栏推荐
猜你喜欢

Two common methods and steps of character device registration

【雅思阅读】王希伟阅读P1(阅读判断题)

Hundreds of continuous innovation to create free low code office tools

Rust string slicing, structs, and enumeration classes

Attributeerror: 'tuple' object has no attribute 'layer' problem solving

Solution to the problem of abnormal display of PDF exported Chinese documents of confluence

为什么网站打开速度慢?

University of Toronto: Anthony coach | the conditions of deep reinforcement learning can induce dynamic risk measurement

How SQLSEVER removes data with duplicate IDS

【AutoSAR 十 IO架构】
随机推荐
Linux软件:如何安装Redis服务
University of Toronto:Anthony Coache | 深度强化学习的条件可诱导动态风险度量
Tensorflow 2. Chapter 15 of X (keras) source code explanation: migration learning and fine tuning
Detailed explanation of pod life cycle
【案例分享】让新时代教育发展与“数”俱进
【AutoSAR 三 RTE概述】
JSON conversion tool class
Introduction of UART, RS232, RS485, I2C and SPI
Pageoffice - bug modification journey
About qbytearray storage hexadecimal and hexadecimal conversion
Rust字符串切片、结构体和枚举类
1.12 - Instructions
[daily training] 871 Minimum refueling times
Multiprocess programming (V): semaphores
Hdu3507 (slope DP entry)
Solution to the problem of abnormal display of PDF exported Chinese documents of confluence
Array common operation methods sorting (including ES6) and detailed use
多进程编程(二):管道
There is an unknown problem in inserting data into the database
NC24840 [USACO 2009 Mar S]Look Up