mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
add 241
This commit is contained in:
parent
85434e2fcf
commit
d1bb439704
67
solutions/241. Different Ways to Add Parentheses.md
Normal file
67
solutions/241. Different Ways to Add Parentheses.md
Normal file
@ -0,0 +1,67 @@
|
||||
# [241. Different Ways to Add Parentheses](https://leetcode.com/problems/different-ways-to-add-parentheses/)
|
||||
|
||||
# 思路
|
||||
给定一个可能含有加减乘的表达式,让我们在任意位置添加括号,求出所有可能表达式的不同值, 我们假设输入的表达式都是合法的.
|
||||
|
||||
由于每个括号内都是一个子表达式, 所以我们考虑用递归来做. 先考虑递归出口, 当表达式就是一个数, 那我们直接返回一个只包含这个数的数组就可以了.
|
||||
再考虑一般情况, 我们可以从前往后遍历输入字符串, 每当遇到运算符我们就把这个位置作为切分点, 递归计算左右两个部分的结果,
|
||||
然后将左右两个结果合并起来push进最终结果数组中.
|
||||
|
||||
我们还可以进一步改进: 用一个hashmap来缓存计算过的表达式的值, 这样如果下次再遇到就不用再次计算了.
|
||||
|
||||
# C++
|
||||
``` C++
|
||||
class Solution {
|
||||
public:
|
||||
vector<int> diffWaysToCompute(string input) {
|
||||
if(input.empty()) return vector<int>();
|
||||
|
||||
vector<int> res;
|
||||
for (int i = 1; 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: left) {
|
||||
for (int k: right) {
|
||||
if (input[i] == '+') res.push_back(j + k);
|
||||
else if (input[i] == '-') res.push_back(j - k);
|
||||
else res.push_back(j * k);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (res.empty()) res.push_back(stoi(input));
|
||||
return res;
|
||||
}
|
||||
};
|
||||
```
|
||||
## hashmap改进
|
||||
``` C++
|
||||
class Solution {
|
||||
public:
|
||||
unordered_map<string, vector<int>> cache;
|
||||
vector<int> diffWaysToCompute(string input) {
|
||||
if(input.empty()) return vector<int>();
|
||||
if(cache.count(input)) return cache[input];
|
||||
vector<int> res;
|
||||
for (int i = 1; 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: left) {
|
||||
for (int k: right) {
|
||||
if (input[i] == '+') res.push_back(j + k);
|
||||
else if (input[i] == '-') res.push_back(j - k);
|
||||
else res.push_back(j * k);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (res.empty()) res.push_back(stoi(input));
|
||||
cache[input] = res;
|
||||
return res;
|
||||
}
|
||||
};
|
||||
```
|
||||
Loading…
Reference in New Issue
Block a user