题目:
给定一串数字和运算符,通过计算所有不同的组编号和运算符的方式返回所有可能的结果。有效的运算符是+,-和*。
输入: "2-1-1"
输出: [0, 2]
说明:
((2-1)-1) = 0
(2-(1-1)) = 2
思路:
枚举每一个运算符,将表达式分成两个子表达式,然后递归求解子表达式,将两个子表达式连接。
说白了这个题就是一个递归。
Code:
const vector<int>& ways(const string& input)
{
vector<int>ans;
for (int i = 0;i<input.length();i++)
{
char op = input[i];
if (op == '+'||op=='-'||op=='*')
{
const string left = input.substr(0, i);
const string right = input.substr(i + 1);
const vector<int>& l = ways(left);
const vector<int>& r = ways(right);
std::function<int(int, int)>f;
switch (op)
{
case '+':f = jihua::add; break;
case '-':f = jihua::minus; break;
case '*':f = jihua::multiply; break;
}
for (int a:l)
{
for (int b:r)
{
ans.push_back(f(a, b));
}
}
}
}
}