1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| class Solution { char[] cs;
public List<Integer> diffWaysToCompute(String expression) { cs = expression.toCharArray(); return dfs(0, cs.length - 1); }
private List<Integer> dfs(int left, int right) { List<Integer> ans = new ArrayList<>(); for (int i = left; i <= right; ++i) { if (cs[i] >= '0' && cs[i] <= '9') continue; List<Integer> l1 = dfs(left, i - 1); List<Integer> l2 = dfs(i + 1, right); for (int a : l1) { for (int b : l2) { int cur = 0; if (cs[i] == '+') cur = a + b; else if (cs[i] == '-') cur = a - b; else cur = a * b; ans.add(cur); } } } if (ans.isEmpty()) { int x = 0; for (int i = left; i <= right; ++i) { x = x * 10 + (cs[i] - '0'); } ans.add(x); } return ans; } }
|