Different Ways to Add Parentheses Given a string expression
of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. You may return the answer in any order.
Example 1:
Input: expression = "2-1-1" Output: [0,2] Explanation: ((2-1)-1) = 0 (2-(1-1)) = 2
Example 2:
Input: expression = "2*3-4*5" Output: [-34,-14,-10,-10,10] Explanation: (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
Constraints:
1 <= expression.length <= 20
expression
consists of digits and the operator'+'
,'-'
, and'*'
.- All the integer values in the input expression are in the range
[0, 99]
.
Different Ways to Add Parentheses Solutions
✅Time: O(2n→n)
✅Space: O(n)
C++
class Solution {
public:
vector<int> diffWaysToCompute(string expression) {
return ways(expression, unordered_map<string, vector<int>>());
}
private:
vector<int> ways(const string& s, unordered_map<string, vector<int>>&& memo) {
if (memo.count(s))
return memo[s];
vector<int> ans;
for (int i = 0; i < s.length(); ++i)
if (ispunct(s[i]))
for (const int a : ways(s.substr(0, i), move(memo)))
for (const int b : ways(s.substr(i + 1), move(memo)))
if (s[i] == '+')
ans.push_back(a + b);
else if (s[i] == '-')
ans.push_back(a - b);
else
ans.push_back(a * b);
return memo[s] = (ans.empty() ? vector<int>{stoi(s)} : ans);
}
};
Java
class Solution {
public List<Integer> diffWaysToCompute(String expression) {
Map<String, List<Integer>> memo = new HashMap<>();
return ways(expression, memo);
}
private List<Integer> ways(final String s, Map<String, List<Integer>> memo) {
if (memo.containsKey(s))
return memo.get(s);
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < s.length(); ++i)
if (!Character.isDigit(s.charAt(i)))
for (final int a : ways(s.substring(0, i), memo))
for (final int b : ways(s.substring(i + 1), memo))
if (s.charAt(i) == '+')
ans.add(a + b);
else if (s.charAt(i) == '-')
ans.add(a - b);
else
ans.add(a * b);
if (ans.isEmpty()) { // single number
memo.put(s, Arrays.asList(Integer.parseInt(s)));
return memo.get(s);
}
memo.put(s, ans);
return ans;
}
}
Python
class Solution:
@lru_cache(None)
def diffWaysToCompute(self, expression: str) -> List[int]:
ans = []
for i, c in enumerate(expression):
if c in '+-*':
for a in self.diffWaysToCompute(expression[:i]):
for b in self.diffWaysToCompute(expression[i + 1:]):
ans.append(eval(str(a) + c + str(b)))
return ans or [int(expression)]
Watch Tutorial
Checkout more Solutions here