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 *
.
Example 1:
Input:"2-1-1"
Output:[0, 2]
Explanation: ((2-1)-1) = 0 (2-(1-1)) = 2
Example 2:
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
思路:
这道题我们主要参考文章:here;这种方法简而言之就是分治的方法,我们遇到运算符的时候就将输入的字符串分离为左右两部分,然后继续进行分割。
解法1 分支方法
class Solution {
public:
vector<int> diffWaysToCompute(string input) {
vector<int> res;
for (int i = 0; i < input.size(); i++) {
if (input[i] == '+' || input[i] == '-' || input[i] == '*' || input[i] == '/') {
vector<int> left = diffWaysToCompute(input.substr(0, i));
vector<int> right = diffWaysToCompute(string(input.begin() + i + 1, input.end()));
for (int l : left) {
for (int r : right) {
switch (input[i]) {
case '+': res.push_back(l + r); break;
case '-': res.push_back(l - r); break;
case '*': res.push_back(l * r); break;
case '/': res.push_back(l / r); break;
default: break;
}
}
}
}
}
if (res.size() == 0) return vector<int>{stoi(input.c_str())};
else return res;
}
};
解法2 分支方法+查找表
class Solution {
public:
vector<int> diffWaysToCompute(string input) {
if (m.find(input) != m.end()) return m[input];
vector<int> res;
for (int i = 0; i < input.size(); i++) {
if (input[i] == '+' || input[i] == '-' || input[i] == '*' || input[i] == '/') {
vector<int> left = diffWaysToCompute(input.substr(0, i));
vector<int> right = diffWaysToCompute(string(input.begin() + i + 1, input.end()));
for (int l : left) {
for (int r : right) {
switch (input[i]) {
case '+': res.push_back(l + r); break;
case '-': res.push_back(l - r); break;
case '*': res.push_back(l * r); break;
case '/': res.push_back(l / r); break;
default: break;
}
}
}
}
}
if (res.size() == 0) res = vector<int>{stoi(input)};
m[input] = res;
return res;
}
private:
map<string, vector<int>> m;
};