leetcode-241:为运算表达式设计优先级

简介: leetcode-241:为运算表达式设计优先级

题目

题目连接

给你一个由数字和运算符组成的字符串 expression ,按不同优先级组合数字和运算符,计算并返回所有可能组合的结果。你可以 按任意顺序 返回答案。

生成的测试用例满足其对应输出值符合 32 位整数范围,不同结果的数量不超过 104 。

示例 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

解题

方法一:dfs(分治)

class Solution {
public:
    vector<int> diffWaysToCompute(string expression) {
        return dfs(0,expression.size()-1,expression);
    }
    vector<int> dfs(int l,int r,string& s){
        vector<int> res;
        for(int i=l;i<=r;i++){
            if(s[i]>='0'&&s[i]<='9') continue;
            vector<int> l1=dfs(l,i-1,s);//分治:获得运算符左侧结果
            vector<int> l2=dfs(i+1,r,s);//分治:获得运算符右侧结果
            for(int a:l1){
                for(int b:l2){
                    int cur=0;
                    if(s[i]=='+') cur=a+b;
                    else if(s[i]=='-') cur=a-b;
                    else cur=a*b;
                    res.push_back(cur);
                }
            }
        }
        if(res.empty()){
            int num=0;
            for(int i=l;i<=r;i++){
                num=num*10+s[i]-'0';
            }
            res.push_back(num);
        }
        return res;
    }
};

相关文章
|
3月前
leetcode:268. 丢失的数字(异或运算)
leetcode:268. 丢失的数字(异或运算)
13 0
|
3月前
leetcode-592:分数加减运算
leetcode-592:分数加减运算
19 0
LeetCode-592 分数加减运算
LeetCode-592 分数加减运算
|
4月前
[leetcode 数位运算] 2939. 最大异或乘积 M
[leetcode 数位运算] 2939. 最大异或乘积 M
|
4月前
[leetcode 数位运算] 2578.最小分割和
[leetcode 数位运算] 2578.最小分割和
LeetCode 1318. 或运算的最小翻转次数
LeetCode 1318. 或运算的最小翻转次数
LeetCode每日一题——592. 分数加减运算
给定一个表示分数加减运算的字符串 expression ,你需要返回一个字符串形式的计算结果。
88 0
Leetcode --- 数学运算问题2
Leetcode --- 数学运算问题2
|
机器学习/深度学习 算法 Serverless
Leetcode --- 数学运算问题1
Leetcode --- 数学运算问题1
|
JavaScript
【leetcode】64. 条件求和,递归+移位运算
**求 1+2+...+n ,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。**
86 0