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

python实践

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

class Solution(object):
    def diffWaysToCompute(self, input):
        """
        :type input: str
        :rtype: List[int]
        """
        result = []
        # print(input[1])
        # print(input[0:])
        # print(input[:2])
        # print(len(input))
        length = len(input)
        ch = ['*', '-', '+']
        for i in range(length):
            if input[i] in ['*', '-', '+']:
                left = self.diffWaysToCompute(input[:i])
                right = self.diffWaysToCompute(input[i+1:])
                for l in left:
                    for r in right:
                        if input[i] == "+":
                            result.append(l+r)
                        elif input[i] == "*":
                            result.append(l*r)
                        elif input[i] == "-":
                            result.append(l-r)
        if not result:
            result.append(int(input))
        return result



if __name__ == '__main__':
    input = "2*3-4*5"
    Solution().diffWaysToCompute(input)

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦