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]
跟构建二叉树的题比较类似,也是采用递归的思路。循环的时候,遇到约算符,就把它的左边,跟右边的组合的结果通过递归的方式取出来,然后嵌套循环遍历左list, 右list,用当前的这个运算符计算结果,保存到result对象里。然后一层层的往上返回。
注: 需要注意,如果当前的子串没有包含运算符的时候,那么对应的for循环它是不会执行的,需要直接将这个字符串转化成数字,保存到result当中。
代码:
public List<Integer> diffWaysToCompute(String input) {
List<Integer> result = new ArrayList<>();
if(input == null || input.length() == 0) return result;
for(int i=0;i<input.length();i++){
char c = input.charAt(i);
if(!isOperator(c)) {
continue;
}
//如果遇到了运算符,那么对左右两边进行计算, 应该是一个递归的调用
List<Integer> left = diffWaysToCompute(input.substring(0, i));
List<Integer> right = diffWaysToCompute(input.substring(i+1));
for(Integer l : left){
for(Integer r: right){
result.add(cal(c, l, r));
}
}
}
if(result.isEmpty()){
result.add(Integer.parseInt(input));
}
return result;
}
private boolean isOperator(char ch){
return (ch == '+') || (ch == '-') || (ch == '*');
}
private Integer cal(char operator, Integer i, Integer j){
switch (operator){
case '+':
return i + j;
case '-':
return i - j;
case '*':
return i * j;
}
return 0;
}