#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <string>
class Solution {
public:
std::vector<int> diffWaysToCompute(std::string expression) {
int len = expression.size();
std::vector<int> ans;
for (int i = 0; i < len; ++i) {
char c = expression[i];
if (c == '+' || c == '-' || c == '*') {
std::vector<int> left = diffWaysToCompute(expression.substr(0, i));
std::vector<int> right = diffWaysToCompute(expression.substr(i + 1));
for (const auto& l : left) {
for (const auto& r : right) {
switch (c) {
case '+':
ans.push_back(l + r);
break;
case '-':
ans.push_back(l - r);
break;
case '*':
ans.push_back(l*r);
break;
}
}
}
}
}
if (ans.empty()) ans.push_back(std::stoi(expression));
return ans;
}
};
int main() {
std::string test = "2 * 3 - 4 * 5";
Solution s;
std::vector<int> res=s.diffWaysToCompute(test);
for (const auto & iter : res) {
std::cout << iter << std::endl;
}
std::cout << std::endl;
std::sort(res.begin(), res.end());
res.erase(std::unique(res.begin(), res.end()),res.end());
for (const auto & iter : res) {
std::cout << iter << std::endl;
}
return 0;
}
看最后的去重操作,先排序,再去重。
结果如图: