把唯一的一个easy刷了,开始medium。
题意:
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”.
((2-1)-1) = 0
(2-(1-1)) = 2
Output: [0, 2]
Example 2
Input: “2*3-4*5”
(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
Output: [-34, -14, -10, -10, 10]
虽说这个题确实用到分治思想了,但我更愿意叫dfs。
就是枚举当前串最后一步运算的是哪个运算符,然后将这个运算符的前后分成两个字符串,递归进行同样的操作。最后统计所有的结果。
唯一要注意的是:不需要去重。
class Solution {
public:
vector<int> diffWaysToCompute(string input) {
vector<int> ans, a, b;
bool flag = 0;
for (int i = 0; i < input.length(); i++) {
if (input[i] == '-') {
flag = true;
a = diffWaysToCompute(input.substr(0, i));
b = diffWaysToCompute(input.substr(i + 1, input.length() - i - 1));
for (int j = 0; j < a.size(); j++)
for (int k = 0; k < b.size(); k++)
ans.push_back(a[j] - b[k]);
}
else if (input[i] == '+') {
flag = true;
a = diffWaysToCompute(input.substr(0, i));
b = diffWaysToCompute(input.substr(i + 1, input.length() - i - 1));
for (int j = 0; j < a.size(); j++)
for (int k = 0; k < b.size(); k++)
ans.push_back(a[j] + b[k]);
}
else if (input[i] == '*') {
flag = true;
a = diffWaysToCompute(input.substr(0, i));
b = diffWaysToCompute(input.substr(i + 1, input.length() - i - 1));
for (int j = 0; j < a.size(); j++)
for (int k = 0; k < b.size(); k++)
ans.push_back(a[j] * b[k]);
}
}
if (!flag) {//纯数字
int x = 0;
for (int i = 0; i < input.length(); i++)
x = x * 10 + input[i] - '0';
ans.push_back(x);
}
return ans;
}
};