Re: [闲聊] 每日leetcode

楼主: dont   2024-09-19 14:21:29
241. Different Ways to Add Parentheses
## 思路
Divide & Conquer
遇到 +,-,* 时
拆成左右两边做recursion再作运算
长度<3的就直接转成数字
1+2*3-4
(1) + (2*3-4) = [1] + [(2*3)-4, 2*(3-4)]
(1+2) * (3-4) = [3] * [-1]
(1+2*3) - (4) = [(1+2)*3, 1+(2*3)] - [4]
## Code
```python
class Solution:
def diffWaysToCompute(self, expression: str) -> List[int]:
@cache
def recur(left, right):
if right - left + 1 < 3:
return [int(expression[left:right+1])]
res = []
for i in range(left, right):
if expression[i] not in {'+', '-', '*'}:
continue
for op1 in recur(left, i-1):
for op2 in recur(i+1, right):
if expression[i] == '+':
res.append(op1 + op2)
elif expression[i] == '-':
res.append(op1 - op2)
else:
res.append(op1 * op2)
return res
return recur(0, len(expression)-1)
```

Links booklink

Contact Us: admin [ a t ] ucptt.com