思路:
参考DISCUSS中的递归。
java code :
public class Solution {
public List<Integer> diffWaysToCompute(String input) {
List<Integer> ans = new ArrayList<Integer>();
for(int i = 0; i < input.length(); ++i) {
if('+' == input.charAt(i) || '-' == input.charAt(i) || '*' == input.charAt(i)) {
String frontPart = input.substring(0, i);
String lastPart = input.substring(i + 1);
List<Integer> ansFrontPart = diffWaysToCompute(frontPart);
List<Integer> ansLastPart = diffWaysToCompute(lastPart);
for(Integer m : ansFrontPart) {
for(Integer n : ansLastPart) {
int res = 0;
switch (input.charAt(i)) {
case '+':
res = m + n;
break;
case '-':
res = m - n;
break;
case '*':
res = m * n;
break;
default:
break;
}
ans.add(res);
}
}
}
}
if(ans.size() == 0) {
ans.add(Integer.parseInt(input));
}
return ans;
}
}