糖逗 发表于 2021-5-2 20:03:38

C++刷LeetCode(241. 为运算表达式设计优先级***)【分治算法】

题目描述:
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。

示例 1:

输入: "2-1-1"
输出:
解释:
((2-1)-1) = 0
(2-(1-1)) = 2
示例 2:

输入: "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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/different-ways-to-add-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


class Solution {
public:
    vector<int> diffWaysToCompute(string expression) {
      vector<int>res;
      int len = expression.size();
      for(int i = 0; i < len; i++){
            char temp = expression;
            if(temp == '+' || temp == '-' || temp == '*'){
                vector<int> left = diffWaysToCompute(expression.substr(0, i));
                vector<int> right = diffWaysToCompute(expression.substr(i+1));
                for(auto cha1 : left){
                  for(auto cha2 : right){
                        if(temp == '+'){
                            res.push_back(cha1 + cha2);
                        }else if(temp == '-'){
                            res.push_back(cha1 - cha2);
                        }else if(temp == '*'){
                            res.push_back(cha1 * cha2);
                        }
                  }
                }
            }
      }
      if(res.empty()){//如果只是单纯的数字,只返回数字本身
            res.push_back(stoi(expression));
      }
      return res;
    }
};


参考链接:https://leetcode-cn.com/problems/different-ways-to-add-parentheses/solution/pythongolang-fen-zhi-suan-fa-by-jalan/
页: [1]
查看完整版本: C++刷LeetCode(241. 为运算表达式设计优先级***)【分治算法】