給你一個(gè)由數(shù)字和運(yùn)算符組成的字符串 expression 拴孤,按不同優(yōu)先級(jí)組合數(shù)字和運(yùn)算符口糕,計(jì)算并返回所有可能組合的結(jié)果譬胎。你可以 按任意順序 返回答案炫七。
生成的測(cè)試用例滿足其對(duì)應(yīng)輸出值符合 32 位整數(shù)范圍爬立,不同結(jié)果的數(shù)量不超過 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;
}
}