卖萌的弱渣

I am stupid, I am hungry.

Different Ways to Add Parentheses.

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

1
2
3
4
5
Input: "2-1-1".

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

Example 2

1
2
3
4
5
6
7
8
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]

Solution

(Different-Ways-to-Add-Parentheses.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution(object):
    def cal(self, a,b,op):
        if op == "+":
            return a+b
        elif op == "-":
            return a-b
        else:
            return a*b

    def dfs(self, nums, ops):
        if not ops:
            return [nums[0]]

        # find split the nums and merge
        ans = []
        for op in range(len(ops)):
            left = self.dfs(nums[:op+1],ops[:op])
            right = self.dfs(nums[op+1:],ops[op+1:])
            for a in left:
                for b in right:
                    ans.append(self.cal(a,b,ops[op]))

        return ans

    def diffWaysToCompute(self, input):
        """
        :type input: str
        :rtype: List[int]
        """
        operator = "+-*"
        nums = []
        ops = []

        # split input
        s = re.split('(\D)', input)
        for i in s:
            if i in operator:
                ops.append(i)
            else:
                nums.append(int(i))

        return self.dfs(nums,ops)