题目:
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 *.
Example1:
Input: “2-1-1”
Output: [0, 2]
Explanation:
((2-1)-1) = 0
(2-(1-1)) = 2
分析:
本题属于divide and conquer(分治法)类型,可以根据string中的运算符进行分割,将原string问题划分成两个substring,分别递归计算运算符两端substring所有可能的结果后,再计算整体所有的结果。
拿题中的例子来说,2-1-1,可以分割成2和1-1两个字符串,分别计算两端的结果后再将结果相减。
class Solution {
private:
string str;
public:
vector<int> diffWaysToCompute(string input) {
str = input;
int N = str.length();
vector<vector<vector<int>>> v(N, vector<vector<int>>(N));
helpfunc(0, N-1, v);
return v[0][N-1];
}
// calculate all the result of substring from start to end
// store result in the v[start][end]
void helpfunc(int start, int end, vector<vector<vector<int>>>& v){
if(v[start][end].size() != 0) return;
bool has_op = false;
for(int i = start; i <= end; i++){
if(is_op(str[i])){
has_op = true;
helpfunc(start, i-1, v);
helpfunc(i+1, end, v);
for(int j = 0; j < v[start][i-1].size(); j++){
for(int k = 0; k < v[i+1][end].size(); k++){
v[start][end].emplace_back(do_op(v[start][i-1][j], v[i+1][end][k], str[i]));
}
}
}
}
// when there is no operation char in the string
// we can directly put it in the vector
if(!has_op){
v[start][end].emplace_back(stoi(str.substr(start, end-start+1)));
}
}
bool is_op(char c){
return c == '+' || c == '-' || c == '*';
}
int do_op(int num1, int num2, char op){
if(op == '+')
return num1 + num2;
if(op == '-')
return num1 - num2;
if(op == '*')
return num1 * num2;
// should never return -1
return -1;
}
};