当前位置:网站首页>leetcode:241. 为运算表达式设计优先级
leetcode:241. 为运算表达式设计优先级
2022-08-04 14:31:00 【OceanStar的学习笔记】
题目来源
题目描述

class Solution {
public:
vector<int> diffWaysToCompute(string expression) {
}
};
题目解析
对于一个形如 x op y(op 为运算符,x 和 y 为数) 的算式而言,它的结果组合取决于 x 和 y 的结果组合数,而 x 和 y 又可以写成形如 x op y 的算式。
因此,该问题的子问题就是x op y中的 x 和 y :以运算符分隔的左右两侧算术解
三步:
- 分解:按照运算符分成左右两部分,分别求解
- 解决:实现一个递归函数,输入算式,返回算式解
- 合并:根据运算符合并左右两部分的解,得出最终解
class Solution {
public:
vector<int> diffWaysToCompute(string exp) {
vector<int> vec1, vec2, res;
int N = exp.size();
int flag = 0;// flag=1说明string是表达式,flag=0说明string是一个数字
for (int i = 0; i < N; ++i) {
if(exp[i] == '+' || exp[i] == '-' || exp[i] == '*'){
flag = 1;
vec1 = diffWaysToCompute(std::string(exp, 0, i));
vec2 = diffWaysToCompute(std::string(exp, i + 1, N - i - 1));
for(int v1 : vec1){
for(int v2 : vec2){
if(exp[i] == '+') res.push_back(v1+v2);
if(exp[i] == '-') res.push_back(v1-v2);
if(exp[i] == '*') res.push_back(v1*v2);
}
}
}
}
if(flag == 0){
return {
std::stoi(exp)};
}
return res;
}
};
边栏推荐
- Centos7 install mysql version rapidly
- 【Web技术】1401- 图解 Canvas 入门
- 没有Project Facets的解决方法
- Rust from entry to proficient 04-variables
- 从理论到实践:MySQL性能优化和高可用架构,一次讲清
- 代码随想录笔记_动态规划_1049最后一块石头的重量II
- 四平方和,激光炸弹
- js深拷贝和浅拷贝具体使用区别_es6深拷贝和浅拷贝
- Crawler - basic use of selenium, no interface browser, other uses of selenium, cookies of selenium, crawler cases
- 【北亚数据恢复】IBM System Storage存储lvm信息丢失数据恢复方案
猜你喜欢

Centos7 install mysql version rapidly

【北亚数据恢复】IBM System Storage存储lvm信息丢失数据恢复方案

谷歌插件.crx文件下载后被自动删除的解决方法

Almost all known protein structures in the world are open sourced by DeepMind

Rust from entry to proficient 04-variables

本周讨论用户体验:Daedalus 的 Nemo 加入 Ambire,探索加密海洋

相似文本聚类与调参

【 HMS core 】 【 Media 】 online video editing service 】 【 material can't show, or network anomalies have been Loading state

Lixia Action | Kyushu Yunzhang Jinnan: Open source is not a movement for a few people, popularization is the source

ICML 2022 | 图神经网络的局部增强
随机推荐
Bluetooth Technology|In the first half of the year, 1.3 million charging piles were added nationwide, and Bluetooth charging piles will become the mainstream of the market
G.登山小分队(暴力&dfs)
How to write SQL statements: the usage of Update, Case, and Select together
CF1527D MEX Tree(mex&树&容斥)
Technology sharing | Description of the electronic fence function in the integrated dispatching system
四平方和,激光炸弹
word2003按空格键为什么会出现小数点
How to automatically renew the token after it expires?
华为手机切换屏幕效果_华为p40页面切换效果怎么换
Execution failed for task ‘:xxx:generateReleaseRFile‘.
【北亚数据恢复】IBM System Storage存储lvm信息丢失数据恢复方案
杭电校赛(逆袭指数)
JCMsuite应用:倾斜平面波传播透过光阑的传输
C# winforms 输入颜色转换颜色名
[LeetCode] 38. Appearance sequence
零基础可以转行软件测试吗 ?这篇文章告诉你
vim 常用操作命令
CCF GLCC正式开营|九州云开源专家携丰厚奖金,助力高校开源推广
【历史上的今天】8 月 4 日:第一位图灵奖女性得主;NVIDIA 收购 MediaQ;首届网络安全挑战大赛完成
相似文本聚类与调参