Leetcode: Different Ways to Add Parentheses

Question

Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *.

Example 1
Input: “2-1-1”.

((2-1)-1) = 0
(2-(1-1)) = 2
Output: [0, 2]

Example 2
Input: “2*3-4*5”

(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10
Output: [-34, -14, -10, -10, 10]

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Show Tags
Show Similar Problems

Solution

Get idea from here.

find subproblem.

class Solution(object):
    def diffWaysToCompute(self, input):
        """ :type input: str :rtype: List[int] """

        result = []
        if input==None or len(input)==0:
            return result

        for ind,elem in enumerate(input):
            if elem.isdigit():
                continue

            left  = self.diffWaysToCompute( input[0:ind] )
            right = self.diffWaysToCompute( input[ind+1:] )

            for temp1 in left:
                for temp2 in right:
                    temp1, tmep2 = int(temp1), int(temp2)
                    if elem=='*':
                        result.append(temp1*temp2)
                    elif elem=='+':
                        result.append(temp1+temp2)
                    elif elem=='-':
                        result.append(temp1-temp2)

        if len(result)==0:
            result.append(int(input))

        return result

你可能感兴趣的:(Leetcode: Different Ways to Add Parentheses)