Java Code:
public class Solution {
public List<Integer> diffWaysToCompute(String input) {
List<Integer> result = new ArrayList<Integer>();
if (input == null || input.length() == 0) {
return result;
}
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c != '+' && c != '-' && c != '*') {
continue;
}
List<Integer> part1Result =
diffWaysToCompute(input.substring(0, i));
List<Integer> part2Result =
diffWaysToCompute(input.substring(i + 1, input.length()));
for (Integer m : part1Result) {
for (Integer n : part2Result) {
if (c == '+') {
result.add(m + n);
} else if (c == '-') {
result.add(m - n);
} else if (c == '*') {
result.add(m * n);
}
}
}
}
if (result.size() == 0) {
result.add(Integer.parseInt(input));
}
return result;
}
}
reference:
https://leetcode.com/discuss/48477/a-recursive-java-solution-284-ms
lz你是ebiz的? 是现在这届?
回复删除咦……你怎么知道的?
删除wo zhen de hao chong bai ni
回复删除谢谢,一下子真么想到怎么写
回复删除好赞!
回复删除