Different Ways to Add Parentheses LeetCode solution in Python
1# Runtime: 49 ms (Top 17.3%) | Memory: 13.54 MB (Top 39.1%)234class Solution(object):5def diffWaysToCompute(self, input):6m = {}7return self.dfs(input, m)89def dfs(self, input, m):10if input in m:11return m[input]12if input.isdigit():13m[input] = int(input)14return [int(input)]15ret = []16for i, c in enumerate(input):17if c in "+-*":18l = self.diffWaysToCompute(input[:i])19r = self.diffWaysToCompute(input[i + 1 :])20ret.extend(eval(str(x) + c + str(y)) for x in l for y in r)21m[input] = ret22return ret