当前位置:网站首页>LeetCode 0241. Design priority for arithmetic expressions - DFS
LeetCode 0241. Design priority for arithmetic expressions - DFS
2022-07-02 00:19:00 【Tisfy】
【LetMeFly】241. Design priorities for operation expressions
Force button topic link :https://leetcode.cn/problems/different-ways-to-add-parentheses/
Give you a string of numbers and operators expression , Combine numbers and operators according to different priorities , Calculate and return the results of all possible combinations . You can In any order Return to the answer .
Example 1:
Input :expression = "2-1-1" Output :[0,2] explain : ((2-1)-1) = 0 (2-(1-1)) = 2
Example 2:
Input :expression = "2*3-4*5" Output :[-34,-14,-10,-10,10] explain : (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
Tips :
1 <= expression.length <= 20expressionBy numbers and operators'+'、'-'and'*'form .- All integer values in the input expression are in the range
[0, 99]
Method 1 :DFS
This problem makes it easy to think of recursion .
We use the function dfs(string s, int l, int r) To compute strings s Of [l, r) What value can a part represent .
vector<int> dfs(string& s, int l, int r) {
// [l, r)
vector<int> ans;
// Code here
return ans;
}
So we just need to call dfs(s, 0, s.size()) that will do .
vector<int> diffWaysToCompute(string& expression) {
return dfs(expression, 0, expression.size());
}
So the next question is dfs How to write a function .
It's not hard .
- If the string
sOf[l, r)If there is no operator in , Recursion ends , We just need to return a unique value .( for example125)if (!hasOp) { // There is no operator ans.push_back(atoi(s.substr(l, r - l).c_str())); } - otherwise , We take all operators as the boundary , Find all possible values on the left side of the operator respectively 、 All possible values on the right , Then do operations one by one , You get a new value .
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); // among OP by +、- or * }
meanwhile , We use hash tables map Record the calculated value .
map<pair<int, int>, vector<int>> ma;
vector<int> dfs(string& s, int l, int r) {
if (ma.count({
l ,r})) // Calculated [l, r) You don't need to calculate it again
return ma[{
l, r}];
// Code Here
return ma[{
l, r}] = ans; // This is the first calculation , Before returning the result, use the incidentally hash table to record , Avoid double counting next time
}
- Time complexity O ( 2 n ) O(2^n) O(2n), among n n n Is the number of operators contained in the original string
- Spatial complexity O ( 2 n ) O(2^n) O(2n)
The specific complexity will not be proved here , But I'm sure I can .
AC Code
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());
}
};
Synchronous posting on CSDN, Originality is not easy. , Reprint please attach Link to the original text Oh ~
Tisfy:https://letmefly.blog.csdn.net/article/details/125555659
边栏推荐
- 2022拼多多详情/拼多多商品详情/拼多多sku详情
- . env. XXX file, with constant, but undefined
- export default 导出的对象,不能解构问题,和module.exports的区别
- Talents come from afar, and Wangcheng district has consolidated the intellectual base of "strengthening the provincial capital"
- The difference between timer and scheduledthreadpoolexecutor
- 二叉搜索树的创建,查找,添加,删除操作
- ADO. Net SqlDataAdapter object
- Window sorting functions rank and deny for SQL data analysis_ rank、raw_ Number and lag, lead window offset function [usage sorting]
- Is it safe and reliable to open an account in Caixue school and make new debts?
- Windows 7 install MySQL error: 1067
猜你喜欢

Heketi record
![[opencv450] hog+svm and hog+cascade for pedestrian detection](/img/55/cdf0bb8231ee59e34c8d5a9d6def23.png)
[opencv450] hog+svm and hog+cascade for pedestrian detection

Graduation season is both a farewell and a new beginning

Download the online video m3u8 tutorial
Linux CentOS7安装Oracle11g的超完美新手教程

SQL Server 安裝指南

EMC circuit protection device for surge and impulse current protection
Linux centos7 installation Oracle11g super perfect novice tutorial

数据库--SqlServer详解

RPA tutorial 01: Excel automation from introduction to practice
随机推荐
Cmake engineering related
【mysql 07】GPG key retrieval failed: “Couldn‘t open file /etc/pki/rpm-gpg/RPM-GPG-KEY-mysql-2022“
Take the enclave Park as a sample to see how Yuhua and Shaoshan play the song of Chang Zhu Tan integrated development
Using multithreaded callable to query Oracle Database
LDR6035智能蓝牙音响可对手机设备持续充放电方案
Use the htaccess file to prohibit the script execution permission in the directory
Linux centos7 installation Oracle11g super perfect novice tutorial
【CMake】Qt creator 里面的 cmake 配置
Is it safe to buy funds in a securities account? Where can I buy funds
UVM tutorial
mysql之B tree 以及 B+tree
SQL数据分析之流程控制语句【if,case...when详解】
Windows installation WSL (II)
Windows 7 install MySQL error: 1067
记录一下大文件上传偶然成功偶然失败问题
Data analysis methodology and previous experience summary [notes dry goods]
Gaussdb (for MySQL):partial result cache, which accelerates the operator by caching intermediate results
使用多线程Callable查询oracle数据库
[opencv450] hog+svm and hog+cascade for pedestrian detection
leetcode96不同的二叉搜索树