1. 为运算表达式设计优先级
给你一个由数字和运算符组成的字符串 expression
,按不同优先级组合数字和运算符,计算并返回所有可能组合的结果。你可以 按任意顺序 返回答案。
生成的测试用例满足其对应输出值符合 32 位整数范围,不同结果的数量不超过 1e4
。
Example
输入:expression = "2-1-1"
输出:[0,2]
代码
class Solution {
private:
enum {ADD = -1, SUB = -2, MUL = -3};
unordered_map<char, int> mp{{'+', ADD},
{'-', SUB},
{'*', MUL}};
unordered_map<int, function<int(int, int)>> op{{ADD, [](int x, int y) { return x + y; }},
{SUB, [](int x, int y) { return x - y; }},
{MUL, [](int x, int y) { return x * y; }}};
public:
vector<int> diffWaysToCompute(const string &expression) {
vector<int> symbol;
for (int i = 0; i < expression.size();) {
if (!isdigit(expression[i])) {
symbol.emplace_back(mp[expression[i++]]);
} else {
int t = 0;
while (i < expression.size() && isdigit(expression[i])) t = t * 10 + expression[i++] - '0';
symbol.emplace_back(t);
}
}
vector<vector<vector<int>>> dp(symbol.size(), vector<vector<int>>(symbol.size()));
for (int i = 0; i < symbol.size(); i += 2) dp[i][i] = {symbol[i]}; // number
for (int i = 3; i <= symbol.size(); ++i) { // operator
for (int j = 0; j + i <= symbol.size(); j += 2) { // number
int l = j, r = j + i - 1;
for (int k = j + 1; k < r; k += 2) { // operator
auto &left = dp[l][k - 1], &right = dp[k + 1][r];
for (auto num1:left) {
for (auto num2:right) dp[l][r].push_back(op[symbol[k]](num1, num2));
}
}
}
}
return dp[0][symbol.size() - 1];
}
};