Leetcode[241] Different Ways to Add Parentheses
29 Nov 2015###Task1 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]
###Python
class Solution(object):
def diffWaysToCompute(self, input):
"""
:type input: str
:rtype: List[int]
"""
ret = []
operators = ['+', '-', '*', '/']
for i in range(len(input)):
if input[i].isdigit():
continue
elif input[i] in operators:
op = input[i]
first = self.diffWaysToCompute(input[:i])
second = self.diffWaysToCompute(input[i + 1:])
for f in first:
for s in second:
ret.append(self.compute(f, s, op))
if len(ret) == 0:
return [int(input)]
return ret
def compute(self, f, s, op):
map = { '+' : lambda f, s: f + s,
'-' : lambda f, s: f - s,
'*' : lambda f, s: f * s,
'/' : lambda f, s: f * 1.0 / s
}
return map[op](f, s)
###Java
public class Solution {
public int compute(int a, int b, char op) {
switch (op) {
case '+' :
return a + b;
case '-' :
return a - b;
case '*' :
return a * b;
default:
break;
}
return 0;
}
public boolean isOperator(char op) {
return (op == '+') || (op == '-') || (op == '*');
}
public List<Integer> diffWaysToCompute(String input) {
List<Integer> res = new ArrayList<Integer>();
if (input == null || input.length() == 0) {
return res;
}
for (int i = 0; i < input.length(); i++) {
char op = input.charAt(i);
if (!isOperator(op)) {
continue;
}
List<Integer> left = diffWaysToCompute(input.substring(0, i));
List<Integer> right = diffWaysToCompute(input.substring(i + 1));
for (int a: left) {
for (int b: right) {
int val = compute(a, b, op);
res.add(val);
}
}
}
if (res.size() == 0) {
res.add(Integer.parseInt(input));
}
return res;
}
}
###Points
- Passed one time!!
- Divide and Conquer