리트코드 241번 Different Ways to Add Parentheses (python)

Kim Yongbin·2023년 10월 6일
0

코딩테스트

목록 보기
124/162

Problem

https://leetcode.com/problems/different-ways-to-add-parentheses/description/

Solution

from typing import List

class Solution:
    def diffWaysToCompute(self, expression: str) -> List[int]:
        def compute(left, right, op):
            results = []
            for l in left:
                for r in right:
                    results.append(eval(str(l) + op + str(r)))
            return results
        
        if expression.isdigit():
            return [int(expression)]
        
        results = []
        for index, value in enumerate(expression):
            if value in "-+*":
                left = self.diffWaysToCompute(expression[:index])
                right = self.diffWaysToCompute(expression[index+1:])
                
                results.extend(compute(left, right, value))
        
        return results

Reference

profile
반박 시 여러분의 말이 맞습니다.

0개의 댓글