当前位置:网站首页>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;
}
};
边栏推荐
- metaRTC5.0新版本支持mbedtls(PolarSSL)
- Oracle RAC环境下vip/public/private IP的区别
- Android Sqlite3基本命令
- C# 动态加载卸载 DLL
- RS|哨兵二号(.SAFE格式)转tif格式
- 爬虫——selenium基本使用、无界面浏览器、selenium的其他用法、selenium的cookie、爬虫案例
- xampp安装包含的组件有(php,perl,apche,mysql)
- 开放麒麟 openKylin 版本规划敲定:10 月发布 0.9 版并开启公测,12 月发布 1.0 版
- xpath获取带命名空间节点注意事项
- 从理论到实践:MySQL性能优化和高可用架构,一次讲清
猜你喜欢
随机推荐
特殊品种的二次开户验资金额
16、学习MySQL 正则表达式
如何在ubuntu环境下安装postgresql并配置远程访问
第十六章 源代码文件 REST API 教程(一)
基于 Next.js实现在线Excel
兆骑科创创新创业大赛活动举办,线上直播路演,投融资对接
字符串类的设计与实现_C语言字符串编程题
【剑指offer33】二叉搜索树的后序遍历序列
Chinese valentine's day, of course, to learn SQL optimization better leave work early to find objects
[LeetCode] 38. Appearance sequence
[Problem solving] QT update component appears "To continue this operation, at least one valid and enabled repository is required"
爬虫——动作链、xpath、打码平台使用
输入输出流总结
token 过期后,如何自动续期?
砺夏行动|九州云章津楠:开源不是少数人的运动,大众化才是源泉
【剑指offer59】队列的最大值
广告电商系统开发功能只订单处理
How to install postgresql and configure remote access in ubuntu environment
idea去掉spark的日志
南瓜科学产品升级 开启益智探索新篇章






![[The Art of Hardware Architecture] Study Notes (1) The World of Metastability](/img/ac/54e4e13d9df90e96933c69623b770e.png)

