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"
.
((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]
思路分析
这道题第一次做的时候没有思路,不知道如何下手,后来看了一下divide and conquer的算法,觉得这道题是一个典型的divide and conquer可以实现的题目,因为operator两边的运算可以可以divide成两个子问题,通过递归的方式来实现。得到operator两边的结果之后,再对这两个结果进行conquer合并得到最后的结果。
class Solution(object):
def diffWaysToCompute(self, input):
"""
:type input: str
:rtype: List[int]
"""
if input.isdigit(): return [int(input)]
result = []
for index, char in enumerate(input):
if char in "+-*":
leftRes = self.diffWaysToCompute(input[:index])
rightRes = self.diffWaysToCompute(input[index+1:])
for num1 in leftRes:
for num2 in rightRes:
if char == "+": res = num1+num2
elif char == "-": res = num1-num2
else: res = num1 * num2
result.append(res)
return result