当前位置:网站首页>LeetCode 0241.为运算表达式设计优先级 - DFS
LeetCode 0241.为运算表达式设计优先级 - DFS
2022-07-02 00:16:00 【Tisfy】
【LetMeFly】241.为运算表达式设计优先级
力扣题目链接:https://leetcode.cn/problems/different-ways-to-add-parentheses/
给你一个由数字和运算符组成的字符串 expression ,按不同优先级组合数字和运算符,计算并返回所有可能组合的结果。你可以 按任意顺序 返回答案。
示例 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
提示:
1 <= expression.length <= 20expression由数字和算符'+'、'-'和'*'组成。- 输入表达式中的所有整数值在范围
[0, 99]
方法一:DFS
这道题让人很容易想到递归。
我们用函数dfs(string s, int l, int r)来计算字符串s的[l, r)部分都能表示什么值。
vector<int> dfs(string& s, int l, int r) {
// [l, r)
vector<int> ans;
// Code here
return ans;
}
因此我们只需要调用dfs(s, 0, s.size())即可。
vector<int> diffWaysToCompute(string& expression) {
return dfs(expression, 0, expression.size());
}
那么接下来的问题就是dfs函数怎么写。
其实也不难。
- 如果字符串
s的[l, r)中没有出现运算符的话,递归结束,我们只需要返回唯一的值即可。(例如125)if (!hasOp) { // 不存在运算符 ans.push_back(atoi(s.substr(l, r - l).c_str())); } - 否则,我们以所有的运算符为分界,分别求出运算符左边的所有可能的值、右边所有可能的值,然后一一对应做运算,就得到了新的值。
if (s[i] == '+' || s[i] == '-' || s[i] == '*') { hasOp = true; vector<int> left = dfs(s, l, i); vector<int> right = dfs(s, i + 1, r); for (auto& a : left) for (auto& b : right) ans.push_back(a OP b); // 其中OP为+、-或* }
同时,我们使用哈希表map记录一下已经求过的值即可。
map<pair<int, int>, vector<int>> ma;
vector<int> dfs(string& s, int l, int r) {
if (ma.count({
l ,r})) // 已经计算过[l, r)的话就不需要再计算一遍
return ma[{
l, r}];
// Code Here
return ma[{
l, r}] = ans; // 这是第一次计算的话,返回结果前用顺便哈希表记录一下,避免下次重复计算
}
- 时间复杂度 O ( 2 n ) O(2^n) O(2n),其中 n n n是原字符串中包含的运算符的个数
- 空间复杂度 O ( 2 n ) O(2^n) O(2n)
具体复杂度这里暂不给出证明,但是肯定能过。
AC代码
C++
class Solution {
private:
map<pair<int, int>, vector<int>> ma;
vector<int> dfs(string& s, int l, int r) {
// [l, r)
if (ma.count({
l ,r}))
return ma[{
l, r}];
vector<int> ans;
bool hasOp = false;
for (int i = l; i < r; i++) {
if (s[i] == '+' || s[i] == '-' || s[i] == '*') {
hasOp = true;
vector<int> left = dfs(s, l, i);
vector<int> right = dfs(s, i + 1, r);
if (s[i] == '+')
for (auto& a : left)
for (auto& b : right)
ans.push_back(a + b);
else if (s[i] == '-')
for (auto& a : left)
for (auto& b : right)
ans.push_back(a - b);
else if (s[i] == '*')
for (auto& a : left)
for (auto& b : right)
ans.push_back(a * b);
}
}
if (!hasOp) {
ans.push_back(atoi(s.substr(l, r - l).c_str()));
}
return ma[{
l, r}] = ans;
}
public:
vector<int> diffWaysToCompute(string& expression) {
return dfs(expression, 0, expression.size());
}
};
同步发文于CSDN,原创不易,转载请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/125555659
边栏推荐
- 使用多线程Callable查询oracle数据库
- [es practice] safe operation mode on ES
- 使用htaccess文件禁止目录里的脚本执行权限
- Multi table operation - one to one, one to many and many to many
- 启牛商学院给的证券账户安不安全?哪里可以开户
- B tree and b+tree of MySQL
- cookie、session、tooken
- Learn online case practice
- Key points of security agreement
- Review data desensitization system
猜你喜欢
![[QT] solve the problem that QT MSVC 2017 cannot compile](/img/35/e458fd437a0bed4bace2d6d65c9ec8.png)
[QT] solve the problem that QT MSVC 2017 cannot compile

回顾数据脱敏系统

Asp .NetCore 微信订阅号自动回复之文本篇

Asp . Text of automatic reply to NETCORE wechat subscription number

Use pair to do unordered_ Key value of map

.env.xxx 文件,加了常量,却undefined

PWN attack and defense world cgpwn2

Algolia's search needs are almost closed

Download the online video m3u8 tutorial

mysql之B tree 以及 B+tree
随机推荐
Use vb Net to convert PNG pictures into icon type icon files
使用htaccess文件禁止目录里的脚本执行权限
cookie、session、tooken
Windows 7 install MySQL error: 1067
RPA tutorial 01: Excel automation from introduction to practice
Jielizhi Bluetooth headset quality control and production skills [chapter]
Correlation - intra group correlation coefficient
基于全志H3的QT5.12.9移植教程
智能运维实战:银行业务流程及单笔交易追踪
[Qt] résoudre le problème que Qt msvc 2017 ne peut pas Compiler
起床困难综合症(按位贪心)
UDS bootloader of s32kxxx bootloader
启牛学院开户安全的吗?开户怎么开?
[QT] solve the problem that QT MSVC 2017 cannot compile
UVM tutorial
Selectively inhibiting learning bias for active sampling
实例讲解将Graph Explorer搬上JupyterLab
Various global files related to [.Net core] program
Windows installation WSL (II)
LeetCode中等题题分享(5)