题目描述

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

链接:https://leetcode-cn.com/problems/different-ways-to-add-parentheses

示例1

  1. 输入: "2-1-1"
  2. 输出: [0, 2]
  3. 解释:
  4. ((2-1)-1) = 0
  5. (2-(1-1)) = 2

示例2

  1. 输入: "2*3-4*5"
  2. 输出: [-34, -14, -10, -10, 10]
  3. 解释:
  4. (2*(3-(4*5))) = -34
  5. ((2*3)-(4*5)) = -14
  6. ((2*(3-4))*5) = -10
  7. (2*((3-4)*5)) = -10
  8. (((2*3)-4)*5) = 10

解题思路

我们知道,一个运算表达式可以理解为 x op y,op代表运算符,x以及y代表子运算表达式,因此x和y又可以拆分成x' op y'的形式,因此可以采用分治算法解决,具体步骤如下,分治算法三步走:

  • 分解:按运算符分成左右两部分,分别求解
  • 解决:实现一个递归函数,输入算式,返回算式解
  • 合并:根据运算符合并左右两部分的解,得出最终解
  1. class Solution {
  2. public:
  3. set<char> ope{'+', '-', '*'};
  4. bool is_digit(string str) {
  5. for (auto ch: str)
  6. if (ope.count(ch))
  7. return false;
  8. return true;
  9. }
  10. vector<int> diffWaysToCompute(string input) {
  11. if (is_digit(input))
  12. return vector<int>{stoi(input)};
  13. vector<int> ret;
  14. for (int i=0; i<input.length(); i++) {
  15. char ch = input[i];
  16. if (ope.count(ch)) {
  17. string left = input.substr(0, i);
  18. string right = input.substr(i+1, input.length()-i-1);
  19. vector<int> left_ret = diffWaysToCompute(left);
  20. vector<int> right_ret = diffWaysToCompute(right);
  21. for (auto value_i: left_ret) {
  22. for (auto value_j: right_ret) {
  23. if (ch == '+')
  24. ret.push_back(value_i+value_j);
  25. else if (ch == '-')
  26. ret.push_back(value_i-value_j);
  27. else
  28. ret.push_back(value_i*value_j);
  29. }
  30. }
  31. }
  32. }
  33. return ret;
  34. }
  35. };