Re: [閒聊] 每日leetcode

看板Marginalman作者 (dont)時間1年前 (2024/09/19 14:21), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串880/1549 (看更多)
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) ``` -- https://i.imgur.com/kyBhy6o.jpeg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 185.213.82.245 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1726726892.A.FB5.html
文章代碼(AID): #1cwyBi-r (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1cwyBi-r (Marginalman)