241. Different Ways to Add Parentheses
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]
给多项式加括号,输出各种结果。
以运算符为基准分割字符串,字符串总的输出结果就等于 左子串结果op右子串结果。
为了加快效率,可以为每个子串记录运算结果,防止重复计算。
class Solution { private: unordered_map<string, vector<int>> result; public: vector<int> diffWaysToCompute(string input) { unsigned int len = input.size(); unsigned int i = 0; vector<int> res; for (; i<len; ++i) { char c = input[i]; if (c == '+' || c == '-' || c == '*') { string s1 = input.substr(0, i); vector<int> v1; v1 = result.find(s1) == result.end()? diffWaysToCompute(s1): result[s1]; string s2 = input.substr(i+1); vector<int> v2; v2 = result.find(s2) == result.end()? diffWaysToCompute(s2): result[s2]; for (auto &n1: v1) for (auto &n2: v2) { if (c == '+') res.push_back(n1 + n2); else if (c == '-') res.push_back(n1 - n2); else res.push_back(n1 * n2); } } } if (res.empty()) res.push_back(stoi(input)); result[input] = res; return res; } };