当前位置:网站首页>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;
}
};
边栏推荐
- C# winforms 输入颜色转换颜色名
- JCMsuite应用:倾斜平面波传播透过光阑的传输
- [机缘参悟-60]:《兵者,诡道也》-1-开篇:“死“与“生“都是天道
- 量化细胞内的信息流:机器学习时代下的研究进展
- 【剑指offer59】队列的最大值
- idea去掉spark的日志
- Crawler - action chain, xpath, coding platform use
- 物联网应用发展趋势
- [Beiya data recovery] IBM System Storage storage lvm information lost data recovery solution
- Kyushu Cloud attended the Navigator Online Forum to discuss the current status, challenges and future of 5G MEC edge computing
猜你喜欢
随机推荐
编程思想_编程有必要给孩子学吗?
[The Art of Hardware Architecture] Study Notes (1) The World of Metastability
九州云出席领航者线上论坛,共话5G MEC边缘计算现状、挑战和未来
【硬件架构的艺术】学习笔记(1)亚稳态的世界
南瓜科学产品升级 开启益智探索新篇章
ASA归因:如何评估关键词的投放价值
B. Construct a simple sequence (greedy)
一看就会的Chromedriver(谷歌浏览器驱动)安装教程
数据库恢复
【剑指offer59】队列的最大值
CCF GLCC officially opened | Kyushu Cloud open source experts bring generous bonuses to help universities promote open source
第六届未来网络发展大会,即将开幕!
小 P 周刊 Vol.13
C# 复制列表
Why does the decimal point appear when I press the space bar in word 2003?
AlphaFold 如何实现 AI 在结构生物学中的全部潜力
centos7安装mysql急速版
1403. 非递增顺序的最小子序列
F. Jinyu and its outer matrix (construction)
Unity插件:使用PopulationSystem制作行走交流的路人








