题目
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。
示例 1:
输入: “2-1-1”
输出: [0, 2]
解释:
((2-1)-1) = 0
(2-(1-1)) = 2
示例 2:
输入: “23-45”
输出: [-34, -14, -10, -10, 10]
解释:
(2*(3-(45))) = -34
((23)-(45)) = -14
((2(3-4))5) = -10
(2((3-4)5)) = -10
(((23)-4)*5) = 10
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/different-ways-to-add-parentheses
分治+记事本 解题
这道题如果能想到分治,我觉得这里就能明白一半
观察解释2
2*3-4*5
其可能的结果为
2*(3-4*5)
2*((3-4)*5)
和2*(3-(4*5))
(2*3)-(4*5)
(2*3-4)*5
((2*3)-4)*5
和(2*(3-4))*5
从小看,或者说从基础看。
我们不难发现,有了俩个元解。即
当表达式是1个数字的时候。我们可以直接返回其结果。加括号没有用。
当表达式是2个数字和一个符号的时候。我们可以直接返回其结果。加括号没有用。
当表达式是3个及以上的数字之后,我们就需要将其看做上面俩个元解的组合了。
从宏观看。
因此当我们遇到一个表达式的时候a op b。我们的结果实际上就是[leftresult] op [rightresult],每一个左边的结果值 op 右边的结果值。而结果值恰好可以根据递归到基础解,或者元解来得到。
谈谈分治,分治实际上和递归有着非常紧密的联系。有点特别像这个公式。
problem(n) = 基础解 + problem(n-1),n代表问题的规模。
还有一种方式是
problem(a, b) = problem(a, k) + problem(k, b),最终可以化为基础解+基础解的方式。
题解1
class Solution {
public:
vector<int> diffWaysToCompute(string input) {
// 这道题需要使用分治的方法
// 假设一个表达式为a op b,我们计算这个表达式需要知道表达式a和b的值。然后通过op计算,就可以得到表达式的值
// 对于input,我们可以将其看做a op b
// 即
// 2 - 1 - 1
// 2 op (1-1) 和 (2-1) op 1的方式。
vector<int> result;
for(size_t i = 0; i < input.size(); i++)
{
char op = input[i];
if(op == '+' || op == '-' || op == '*')
{
auto leftResult = diffWaysToCompute(input.substr(0, i));
auto rightResult = diffWaysToCompute(input.substr(i+1));
for(auto leftValue : leftResult)
{
for(auto rightValue : rightResult)
{
switch(op)
{
case '+':
result.push_back(leftValue + rightValue);
break;
case '-':
result.push_back(leftValue - rightValue);
break;
case '*':
result.push_back(leftValue * rightValue);
break;
default:
;
}
}
}
}
}
if(result.empty())
{
result.push_back(stoi(input));
}
return result;
}
};
题解2
很容易就可以看到,我们有些表达式的值会多次计算。因此使用记事本来记录他们的值。
class Solution {
public:
using MapType = unordered_map<string, vector<int>>;
vector<int> diffWaysToCompute(string input) {
int n = input.size();
if(!n)
return {};
MapType memo;
return partition(input, memo);
}
vector<int> partition(const string& input, MapType& memo)
{
if(!memo.count(input))
{
vector<int> result;
for(int i = 0; i < input.size(); i++)
{
char op = input[i];
if(op == '+' || op == '-' || op == '*')
{
auto leftResult = partition(input.substr(0, i), memo);
auto rightResult = partition(input.substr(i+1), memo);
for(auto leftValue : leftResult)
{
for(auto rightValue : rightResult)
{
if(op == '+')
{
result.push_back(leftValue + rightValue);
}else if(op == '-') {
result.push_back(leftValue - rightValue);
}else{
result.push_back(leftValue * rightValue);
}
}
}
}
}
if(result.empty())
{
result.push_back(stoi(input));
}
memo[input] = result;
}
return memo[input];
}
}