題目:
python
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 *
.算法
大意是給定一個運算,求解全部運算序列的解app
例如ide
Input: "2*3-4*5"
spa
(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]
code
算法思路:orm
將運算轉換成棧過程,這樣就將問題轉換成一個遞歸問題遞歸
即每一步分爲兩種走法:input
1)繼續向棧中添加數字與運算符
string
2)彈出2個數字1個運算符進行計算
代碼:
class Solution(object): def addOperatorAndNumber(self, inputList, stack): if len(inputList) < 2: return [] stack.append(inputList[0]) stack.append(inputList[1]) inputList = inputList[2:] return self.calculate(inputList,stack) def calculateTopStack(self, inputList, stack): number1 = int(stack.pop()) operator = stack.pop() number2 = int(stack.pop()) if operator == "+": stack.append(number1 + number2) elif operator == "-": stack.append(number2 - number1) elif operator == "*": stack.append(number1 * number2) return self.calculate(inputList,stack) def calculate(self, inputList, stack): if len(stack) == 1: if len(inputList) == 0: return [stack[0]] else: return self.addOperatorAndNumber(inputList,stack) result1 = self.calculateTopStack(inputList[:], stack[:]) result2 = self.addOperatorAndNumber(inputList[:],stack[:]) result1.extend(result2) return result1 def diffWaysToCompute(self, input): """ :type input: str :rtype: List[int] """ input = input.replace('+'," + ") input = input.replace("-"," - ") input = input.replace("*"," * ") inputList = input.split(" ") stack = [int(inputList[0])] return self.calculate(inputList[1:],stack)