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]
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
因为需要用到 vector,所以选用了c++,代码如下:
#include <iostream>
#include <vector>
#include <string>
#include <stdlib.h>
using namespace std;
class Solution {
public:
vector<int> diffWaysToCompute(string input) {
vector<int> result;
for(int i = 0; i < input.length(); i++) {
if(input[i] == '+' || input[i] == '-' || input[i] == '*') {
vector<int> left = diffWaysToCompute(input.substr(0,i));
vector<int> right = diffWaysToCompute(input.substr(i+1));
for(int j = 0 ; j < left.size(); j++) {
for(int k = 0; k < right.size(); k++) {
if(input[i] == '+') {
result.push_back(left[j] + right[k]);
} else if(input[i] == '-') {
result.push_back(left[j] - right[k]);
} else {
result.push_back(left[j] * right[k]);
}
}
}
}
}
if(result.empty())
result.push_back(atoi(input.c_str()));
return result;
}
};
int main() {
string input;
cin >> input;
Solution s;
vector<int> r = s.diffWaysToCompute(input);
for(vector<int>::iterator iter = r.begin(); iter != r.end(); ++iter) {
cout << *iter << endl;
}
return 0;
}
暂时想到这,过第二遍的时候有好的算法再改进。