From d1bb4397046548ad9daaec6ccb92af60fb10472c Mon Sep 17 00:00:00 2001 From: ShusenTang Date: Sun, 20 Oct 2019 15:23:01 +0800 Subject: [PATCH] add 241 --- .../241. Different Ways to Add Parentheses.md | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 solutions/241. Different Ways to Add Parentheses.md diff --git a/solutions/241. Different Ways to Add Parentheses.md b/solutions/241. Different Ways to Add Parentheses.md new file mode 100644 index 0000000..f40de8b --- /dev/null +++ b/solutions/241. Different Ways to Add Parentheses.md @@ -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 diffWaysToCompute(string input) { + if(input.empty()) return vector(); + + vector res; + for (int i = 1; i < input.size(); ++i) { + // 从运算符分开分别递归计算两边 + if (input[i] == '+' || input[i] == '-' || input[i] == '*') { + vector left = diffWaysToCompute(input.substr(0, i)); + vector 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> cache; + vector diffWaysToCompute(string input) { + if(input.empty()) return vector(); + if(cache.count(input)) return cache[input]; + vector res; + for (int i = 1; i < input.size(); ++i) { + // 从运算符分开分别递归计算两边 + if (input[i] == '+' || input[i] == '-' || input[i] == '*') { + vector left = diffWaysToCompute(input.substr(0, i)); + vector 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; + } +}; +```