给你一个由数字和运算符组成的字符串 expression ,按不同优先级组合数字和运算符,计算并返回所有可能组合的结果。你可以 按任意顺序 返回答案。
生成的测试用例满足其对应输出值符合 32 位整数范围,不同结果的数量不超过 104 。
示例 1:
输入:expression = "2-1-1"
输出:[0,2]
解释:
((2-1)-1) = 0
(2-(1-1)) = 2
示例 2:
输入:expression = "23-45"
输出:[-34,-14,-10,-10,10]
解释:
(2(3-(45))) = -34
((23)-(45)) = -14
((2(3-4))5) = -10
(2((3-4)5)) = -10
(((23)-4)5) = 10
class Solution {
public List<Integer> cal2(String[] arr) {
if (arr.length == 1) {
return Arrays.asList(Integer.parseInt(arr[0]));
}
if (arr.length == 0) {
return new ArrayList<>();
}
List<Integer> res = new ArrayList<>();
for (int i = 0; i <= arr.length-2; i++) {
if (arr[i].equals("+") || arr[i].equals("-") || arr[i].equals("*")) {
continue;
} else {
List<Integer> left = cal2(Arrays.copyOfRange(arr, 0, i+1));
List<Integer> right = cal2(Arrays.copyOfRange(arr, i+2, arr.length));
for (int j = 0; j < left.size(); j++) {
for (int k = 0; k < right.size(); k++) {
if (arr[i+1].equals("+")) {
res.add(left.get(j) + right.get(k));
} else if (arr[i+1].equals("-")) {
res.add(left.get(j) - right.get(k));
} else if (arr[i+1].equals("*")) {
res.add(left.get(j) * right.get(k));
}
}
}
}
}
return res;
}
public List<Integer> diffWaysToCompute(String expression) {
List<String> list = new ArrayList<>();
String curStr = "";
for (int i = 0; i < expression.length(); i++) {
if (Character.isDigit(expression.charAt(i))) {
curStr += String.valueOf(expression.charAt(i));
} else {
list.add(curStr);
list.add(String.valueOf(expression.charAt(i)));
curStr = "";
}
}
list.add(curStr);
String[] str = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
str[i] = list.get(i);
}
List<Integer> res = cal2(str);
return res;
}
}