Description:
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:
Input: "2-1-1".
((2-1)-1) = 0
(2-(1-1)) = 2
Output: [0, 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]
Link:
https://leetcode.com/problems/different-ways-to-add-parentheses/description/
解题方法:
分治算法。
Tips:
先遍历一遍字符串将数字储存好。
Time Complexity:
O(N^3)
完整代码:
vector<int> diffWaysToCompute(string input)
{
vector<int> trf;
if(input.size() == 0)
return {};
string temp;
for(char ch: input)
{
if(ch == '+' || ch == '-' || ch == '*')
{
trf.push_back(std::atoi(temp.c_str()));
temp.clear();
trf.push_back(ch * -1);
}
else
temp += ch;
}
trf.push_back(std::atoi(temp.c_str()));
return helper(0, trf.size() - 1, trf);
}
vector<int> helper(int start, int end, vector<int>& trf)
{
if(start == end)
return {trf[start]};
vector<int> result;
for(int i = start; i <= end; i++)
{
if(trf[i] < 0)
{
vector<int> left = helper(start, i - 1, trf);
vector<int> right = helper(i + 1, end, trf);
for(int l: left)
{
for(int r: right)
{
switch(trf[i])
{
case -'+':
result.push_back(l + r);
break;
case -'-':
result.push_back(l - r);
break;
case -'*':
result.push_back(l * r);
break;
}
}
}
}
}
return result;
}