当前位置:网站首页>leetcode: 241. Designing precedence for arithmetic expressions
leetcode: 241. Designing precedence for arithmetic expressions
2022-08-04 14:37:00 【OceanStar's study notes】
题目来源
题目描述

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 :Left and right arithmetic solutions separated by operators
三步:
- 分解:Divided into left and right parts according to the operator,分别求解
- 解决:实现一个递归函数,输入算式,返回算式解
- 合并:根据运算符合并左右两部分的解,得出最终解
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;
}
};
边栏推荐
猜你喜欢

【剑指offer33】二叉搜索树的后序遍历序列

FRED Application: Capillary Electrophoresis System

【模型部署与业务落地】基于量化芯片的损失分析

xampp安装包含的组件有(php,perl,apche,mysql)

ASA归因:如何评估关键词的投放价值

砺夏行动|九州云章津楠:开源不是少数人的运动,大众化才是源泉

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

leetcode:254. 因子的组合

1401 - Web technology 】 【 introduction to graphical Canvas

技术分享| 融合调度系统中的电子围栏功能说明
随机推荐
【Web技术】1401- 图解 Canvas 入门
leetcode:255 验证前序遍历序列二叉搜索树
B. Construct a simple sequence (greedy)
【剑指offer59】队列的最大值
【HMS core】【Media】【视频编辑服务】 在线素材无法展示,一直Loading状态或是网络异常
Sum of four squares, laser bombs
关于redis的几件小事(五)redis保证高并发以及高可用
Notes for xpath getting node with namespace
vim common operation commands
X射线掠入射聚焦反射镜
leetcode:241. 为运算表达式设计优先级
Makefile syntax and usage notes
leetcode:253. 至少需要多少间会议室
Hangzhou Electric School Competition (Counter Attack Index)
【模型部署与业务落地】基于量化芯片的损失分析
用了TCP协议,就一定不会丢包吗?
集合划分差最小问题(01背包)
FRED应用:毛细管电泳系统
How to install postgresql and configure remote access in ubuntu environment
数据库恢复