Leetcode 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”
Output: [0, 2]
Explanation:
((2-1)-1) = 0
(2-(1-1)) = 2
Example 2:
Input: “23-45”
Output: [-34, -14, -10, -10, 10]
Explanation:
(2*(3-(45))) = -34
((23)-(45)) = -14
((2(3-4))5) = -10
(2((3-4)5)) = -10
(((23)-4)*5) = 10
题目大意:
给定一个字符串表达式,可以在任意位置加(),求可以得到的所有答案。
解题思路:
我们把字符串看作“()运算符()”的形式,则可以采用分治法来解决。以运算符为分界将输入的字符串分成左右两部分,用一个left和一个right数组分别记录左右括号得到的所有计算结果,再从左右分别取数字出来做特定运算符的运算。可以采用自递归的形式,停止条件为被分解的字符串只剩一个数字,则该数字为该子字符串的唯一计算结果。如果原始输入的字符串只有单个数字或者为空,则返回转换为整型后的结果。时间复杂度为O(2的n次方 * n的平方),其中枚举括号为2^n,左右取元素计算为n的平方。
代码1:
class Solution {
public:
vector<int> diffWaysToCompute(string input) {
vector<int> res;
for(int i = 0; i < input.size(); i++)
{
if(input[i] == '+' || input[i] == '-' || input[i] == '*')
{
vector<int> left = diffWaysToCompute(input.substr(0, i));
vector<int> right = diffWaysToCompute(input.substr(i + 1));
for(int j = 0; j < left.size(); j++)
{
for(int k = 0; k < right.size(); k++)
{
if(input[i] == '+')
res.push_back(left[j] + right[k]);
else if(input[i] == '-')
res.push_back(left[j] - right[k]);
else
res.push_back(left[j] * right[k]);
}
}
}
}
if(res.empty())
res.push_back(stoi(input));
return res;
}
};
代码2:
用哈希表记录已经计算过的答案,用空间换时间
class Solution {
public:
unordered_map<string, vector<int>> memo;
vector<int> diffWaysToCompute(string input) {
if(memo.count(input)) return memo[input];
vector<int> res;
for(int i = 0; i < input.size(); i++)
{
if(input[i] == '+' || input[i] == '-' || input[i] == '*')
{
vector<int> left = diffWaysToCompute(input.substr(0, i));
vector<int> right = diffWaysToCompute(input.substr(i + 1));
for(int j = 0; j < left.size(); j++)
{
for(int k = 0; k < right.size(); k++)
{
if(input[i] == '+')
res.push_back(left[j] + right[k]);
else if(input[i] == '-')
res.push_back(left[j] - right[k]);
else
res.push_back(left[j] * right[k]);
}
}
}
}
if(res.empty())
res.push_back(stoi(input));
memo[input] = res;
return res;
}
};
参考资料:
https://www.cnblogs.com/grandyang/p/4682458.html