确实是分治的好题。碰到符号,就递归处理当前符号左右两边的,递归到当前表达式只剩一个数字的时候,将这个字符数字转为数字返回。用两个数组去接返回回来的值,然后遍历两个数组,根据当前符号来将res数组中的数字做对应的操作,为什么两边返回出来的是两个数组?因为两边也有可能是一个复杂的表达式,可能会返回多种情况,双重循环遍历r1和r2。加入res。
如果循环过后res为空,证明input是一个简单的数字,直接将其加入res
class Solution {
public:
vector<int> diffWaysToCompute(string input) {
//递归+分治
//比如2-1-1,碰到第一个负号就一种情况,计算-号左右的2和1-1
//然后计算第二个负号两侧的1和1。
//第二种情况就是碰到第二个负号,计算-号左右的2-1和1
//然后计算第一个负号两侧的2和1
vector<int> res;
for(int i = 0; i < input.length(); ++i){
char c = input[i];
if(c == '-' || c== '+' || c=='*'){
auto res1 = diffWaysToCompute(input.substr(0,i));
auto res2 = diffWaysToCompute(input.substr(i+1));
//此时的res1和res2是两个数组
for(auto r1 : res1){
for(auto r2 : res2){
if(c == '-'){
res.push_back(r1-r2);
}
else if(c == '+'){
res.push_back(r1+r2);
}
else{
res.push_back(r1*r2);
}
}
}
}
}
//如果传进来的input就是一个数字,就直接返回这个字符串的int形式
if(res.empty()){
res.push_back(stoi(input));
}
return res;
}
};