【题目】给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +
, -
以及 *
。
public class DiffWaysToCompute {
public List<Integer> diffWaysToCompute(String input) {
ArrayList<Integer> res = new ArrayList<>();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c == '+' || c == '-' || c == '*') {
List<Integer> res1 = diffWaysToCompute(input.substring(0, i));
List<Integer> res2 = diffWaysToCompute(input.substring(i + 1));
for (Integer r1 : res1) {
for (Integer r2 : res2) {
if (c == '+') {
res.add(r1 + r2);
} else if (c == '-') {
res.add(r1 - r2);
} else if (c == '*') {
res.add(r1 * r2);
}
}
}
}
}
if (res.isEmpty()) {
res.add(Integer.valueOf(input));
}
return res;
}
}