Recursive split with memo
Time Catalan-number output size Space Memo of substringsFor each operator, combine all results of the left and right substrings. A string without operators is a number.
expression = "2*3-4*5"parts(map)
out(list)
Step 1/4Last operation is the first *: left 2, right "3-4*5" has two answers (-17, -5). 2 × -17 = -34, 2 × -5 = -10.
import java.util.*;
class Solution {
private final Map<String, List<Integer>> memo = new HashMap<>();
public List<Integer> diffWaysToCompute(String expression) {
if (memo.containsKey(expression)) return memo.get(expression);
List<Integer> out = new ArrayList<>();
for (int i = 0; i < expression.length(); i++) {
char op = expression.charAt(i);
if (op != '+' && op != '-' && op != '*') continue;
for (int a : diffWaysToCompute(expression.substring(0, i)))
for (int b : diffWaysToCompute(expression.substring(i + 1)))
out.add(op == '+' ? a + b : op == '-' ? a - b : a * b);
}
if (out.isEmpty()) out.add(Integer.parseInt(expression));
memo.put(expression, out);
return out;
}
}Verdict: Same split structure as interval DP.