1 minute read

241. Different Ways to Add Parentheses

문제 링크

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

문제 설명

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.

The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed 10^4.

제한 사항

  • 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].

입출력 예 #1

  1. Input : expression = “2-1-1”
  2. Output : [0,2]
  3. Explanation : ((2-1)-1) = 0

(2-(1-1)) = 2

입출력 예 #2

  1. Input : expression = “23-45”
  2. Output : [-34,-14,-10,-10,10]
  3. Explanation : (2(3-(45))) = -34

((23)-(45)) = -14

((2(3-4))5) = -10

(2((3-4)5)) = -10

(((23)-4)5) = 10

문제 풀이

기호를 기준으로 왼쪽 오른쪽으로 분할하고 계산 결과를 합치면서 나오는 조합들을 배열에 넣는다.

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

Comments