Different Ways to Add Parentheses — LeetCode 241 Python Solution
- Problem
- #241
- Pattern
- Dynamic Programming
- Reading time
- 4 min
- Source
- leetcode.com
The problem
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
- Input
- expression = "2-1-1"
- Output
- [0,2]
- Explanation
- ((2-1)-1) = 0
Python solution
class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
@cache
def dfs(exp):
if exp.isdigit():
return [int(exp)]
ans = []
for i, c in enumerate(exp):
if c in '-+*':
left, right = dfs(exp[:i]), dfs(exp[i + 1 :])
for a in left:
for b in right:
if c == '-':
ans.append(a - b)
elif c == '+':
ans.append(a + b)
else:
ans.append(a * b)
return ans
return dfs(expression)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 241. Different Ways to Add Parentheses is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming and Memoization.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 241. Different Ways to Add Parentheses?
- LeetCode 241. Different Ways to Add Parentheses is rated Medium on LeetCode.
- What topics does LeetCode 241. Different Ways to Add Parentheses cover?
- LeetCode 241. Different Ways to Add Parentheses is tagged Recursion, Memoization, Math, String and Dynamic Programming on LeetCode.