Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +
, -
and *
.
Copy Input: "2-1-1"
Output: [0, 2]
Explanation:
((2-1)-1) = 0
(2-(1-1)) = 2
Copy Input: "2*3-4*5"
Output: [-34, -14, -10, -10, 10]
Explanation:
(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
Copy class Solution {
public:
vector<int> diffWaysToCompute(string input) {
vector<int> nums;
vector<char> ops;
preprocess(input, nums, ops);
return diffWaysToCompute(nums, ops, 0, nums.size() - 1);
}
inline void preprocess(string &input, vector<int> &nums, vector<char> &ops) {
int d = input.front() - '0';
for (int i = 1; i < input.size(); ++i) {
if (!isdigit(input[i])) {
nums.push_back(d);
ops.push_back(input[i]);
d = 0;
} else {
d = (d * 10) + (input[i] - '0');
}
}
nums.push_back(d);
}
inline int calc(char op, int n1, int n2) {
switch (op) {
case '+':
return n1 + n2;
case '-':
return n1 - n2;
default:
return n1 * n2;
}
}
vector<int> diffWaysToCompute(vector<int> &nums, vector<char> &ops, int begin, int end) {
if (begin == end) return vector<int>{nums[begin]};
vector<int> results;
for (int i = begin; i < end; ++i) {
const vector<int> &left = diffWaysToCompute(nums, ops, begin, i);
const vector<int> &right = diffWaysToCompute(nums, ops, i + 1, end);
for (const auto l: left) {
for (const auto r: right) {
results.push_back(calc(ops[i], l, r));
}
}
}
return results;
}
};