[分治]241. Different Ways to Add Parentheses

  • 分类:分治
  • 时间复杂度: O(nlogn)

241. 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:

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

Example 2:

Input: "2*3-4*5"
Output: [-34, -14, -10, -10, 10]
Explanation: 
(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

代码:

分治方法:

class Solution:
    def diffWaysToCompute(self, input):
        """
        :type input: str
        :rtype: List[int]
        """
        ans=[]
        if input==None and len(input)==0:
            return ans

        return self.getResult(input)

    def getResult(self, input):
        if ("+" not in input) and ("-" not in input) and ("*" not in input):
            return [int(input)]
        res=[]
        for i in range(len(input)):
            if not input[i].isdigit():
                res+=self.decare(self.getResult(input[:i]),self.getResult(input[i+1:]),input[i])
        return res

    def decare(self,array1,array2,op):
        res=[]
        for a in array1:
            for b in array2:
                if op=="+":
                    res.append(a+b)
                elif op=="-":
                    res.append(a-b)
                else:
                    res.append(a*b)
        return res

讨论:

1.一开始看到这道题的时候,看见括号,还以为要用stack。听完讲解之后发现还是用分治,说不定还能用树做???
2.知识点:分治+笛卡尔集


[分治]241. Different Ways to Add Parentheses_第1张图片
241

你可能感兴趣的:([分治]241. Different Ways to Add Parentheses)