https://leetcode.com/problems/different-ways-to-add-parentheses/
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]
Code
class Solution(object): def diffWaysToCompute(self, input): if input.isdigit(): return [int(input)] res = [] for i in xrange(len(input)): if input[i] in "-+*": res1 = self.diffWaysToCompute(input[:i]) res2 = self.diffWaysToCompute(input[i+1:]) res += [eval(str(k)+input[i]+str(j)) for k in res1 for j in res2] return res
Idea
Deal it with recursion. Whenever you see an operator (`-`, `+` or `*`), you get results from the operator’s left side (line 8) and right side (line 9) and concatenate results from both sides with the operator (line 10) . Remember that to judge if a string represents a pure number you can use `string.isdigit()`. (line 3)
Reference
https://leetcode.com/discuss/53566/python-easy-to-understand-solution-divide-and-conquer