Copy Input: expression = "2-1-1"
Output: [0,2]
Explanation:
((2-1)-1) = 0
(2-(1-1)) = 2
Copy Input: expression = "2*3-4*5"
Output: [-34,-14,-10,-10,10]
Explanation:
(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
Copy class Solution
{
public:
vector<int> compute(string s)
{
vector<int> v;
for (int i = 0; i < s.length(); i++)
{
if (s[i] == '+' || s[i] == '-' || s[i] == '*')
{
string ls = s.substr(0, i);
string rs = s.substr(i+1, s.length() - i+1);
vector<int> la = compute(ls);
vector<int> ra = compute(rs);
for (int j = 0; j < la.size(); j++)
{
for (int k = 0; k < ra.size(); k++)
{
if (s[i] == '-')
{
v.push_back(la[j] - ra[k]);
}
if (s[i] == '+')
{
v.push_back(la[j] + ra[k]);
}
if (s[i] == '*')
{
v.push_back(la[j] * ra[k]);
}
}
}
}
}
if(v.size() == 0){
v.push_back(stoi(s));
}
return v;
}
vector<int> diffWaysToCompute(string s)
{
vector<int> res = compute(s);
return res;
}
};
Copy class Solution
{
public:
vector<int> compute(string s, unordered_map<string, vector<int>> &m)
{
vector<int> v;
if (m.find(s) != m.end())
{
return m[s];
}
for (int i = 0; i < s.length(); i++)
{
if (s[i] == '+' || s[i] == '-' || s[i] == '*')
{
string ls = s.substr(0, i);
string rs = s.substr(i + 1, s.length() - i + 1);
vector<int> la = compute(ls, m);
vector<int> ra = compute(rs, m);
for (int j = 0; j < la.size(); j++)
{
for (int k = 0; k < ra.size(); k++)
{
if (s[i] == '-')
{
v.push_back(la[j] - ra[k]);
}
if (s[i] == '+')
{
v.push_back(la[j] + ra[k]);
}
if (s[i] == '*')
{
v.push_back(la[j] * ra[k]);
}
}
}
}
}
if (v.size() == 0)
{
v.push_back(stoi(s));
}
m[s] = v;
return v;
}
vector<int> diffWaysToCompute(string s)
{
unordered_map<string, vector<int>> m;
vector<int> res = compute(s, m);
return res;
}
};