class Solution {
public:
void get_result(const vector<int>&digits, const vector<char>& sign, int left, int right, vector<int>&result){
if(left == right){
result.push_back(digits[left]);
return;
}
for(int i = left; i < right; ++i){
vector<int> left_result, right_result;
get_result(digits, sign, left, i, left_result);
get_result(digits, sign, i+1, right, right_result);
for(const auto left_res: left_result){
for(const auto right_res: right_result){
switch(sign[i]){
case('+'):
result.push_back(left_res + right_res);
break;
case('-'):
result.push_back(left_res - right_res);
break;
case('*'):
result.push_back(left_res * right_res);
break;
}
}
}
}
return;
}
vector<int> diffWaysToCompute(string input) {
//first, parse the string
vector<int> digits;
vector<char> sign;
int len = input.length();
vector<int> ret;
if(len == 0){
return ret;
}
int digits_peek = 0, sign_peek = 0;
for(int i = 0; i < len;){
int left = i;
while(i < len && input[i] != '+' && input[i] != '-' && input[i] != '*'){ //input[i] are digits
++i;
}
digits.push_back(atoi(input.substr(left, i - left).c_str()));
if(i < len){ //input[i] is an operator
sign.push_back(((char)input[i]));
}
++i;
}
int digits_size = digits.size();
int sign_size = sign.size();
if(sign_size == 0){
ret.push_back(digits[0]);
return ret;
}
if(sign_size < 2){
int cal;
switch(sign[0]){
case('+'):
cal = digits[0] + digits[1];
break;
case('-'):
cal = digits[0] - digits[1];
break;
case('*'):
cal = digits[0] * digits[1];
break;
}
ret.push_back(cal);
return ret;
}
//next, enumerate splitting point
for(int i = 0; i < sign_size; ++i){
vector<int> left_result, right_result;
get_result(digits, sign, 0, i, left_result);
get_result(digits, sign, i + 1, digits_size - 1, right_result);
for(const auto left_res: left_result){
for(const auto right_res: right_result){
switch(sign[i]){
case('+'):
ret.push_back(left_res + right_res);
break;
case('-'):
ret.push_back(left_res - right_res);
break;
case('*'):
ret.push_back(left_res * right_res);
break;
}
}
}
}
return ret;
}
};
Tip:
1. before coding:
* complexity estimation ( backtracking )
* corner case (no sign at all, one sign, no bracket at all)
* recursion
2. how to figure out a solution?
mock your thinking method