This is a classic algorithm problem.
The DP solution is indeed n^3.
I'm using recursion with memoization below.
I need some detailed explanation of what is the runtime of the code below? I'm not satisfied with the current answer. Can someone help?
public static int countParenthesization(String expr, int begin, int end, boolean result, Map<String, Integer> lookup) {
String lookupKey = begin + "-" + end + "-" + result;
if (end - begin == 0) {
String currenExpr = expr.charAt(begin) + "";
int count = (currenExpr.equals("T") && result) || (currenExpr.equals("F") && !result) ? 1 : 0;
lookup.put(lookupKey, count);
return count;
}
if (lookup.containsKey(lookupKey)) {
return lookup.get(lookupKey);
}
int count = 0;
for (int i = begin + 1; i <= end; i = i + 2) {
int leftBegin = begin;
int leftEnd = i - 1;
int rightBegin = i + 1;
int rightEnd = end;
switch (expr.charAt(i)) {
case '|':
if (result) {
count += countParenthesization(expr, leftBegin, leftEnd, true, lookup)
* countParenthesization(expr, rightBegin, rightEnd, true, lookup);
count += countParenthesization(expr, leftBegin, leftEnd, true, lookup)
* countParenthesization(expr, rightBegin, rightEnd, false, lookup);
count += countParenthesization(expr, leftBegin, leftEnd, false, lookup)
* countParenthesization(expr, rightBegin, rightEnd, true, lookup);
} else {
count += countParenthesization(expr, leftBegin, leftEnd, false, lookup)
* countParenthesization(expr, rightBegin, rightEnd, false, lookup);
}
break;
case '&':
if (result) {
count += countParenthesization(expr, leftBegin, leftEnd, true, lookup)
* countParenthesization(expr, rightBegin, rightEnd, true, lookup);
} else {
count += countParenthesization(expr, leftBegin, leftEnd, true, lookup)
* countParenthesization(expr, rightBegin, rightEnd, false, lookup);
count += countParenthesization(expr, leftBegin, leftEnd, false, lookup)
* countParenthesization(expr, rightBegin, rightEnd, true, lookup);
count += countParenthesization(expr, leftBegin, leftEnd, false, lookup)
* countParenthesization(expr, rightBegin, rightEnd, false, lookup);
}
break;
case '^':
if (result) {
count += countParenthesization(expr, leftBegin, leftEnd, true, lookup)
* countParenthesization(expr, rightBegin, rightEnd, false, lookup);
count += countParenthesization(expr, leftBegin, leftEnd, false, lookup)
* countParenthesization(expr, rightBegin, rightEnd, true, lookup);
} else {
count += countParenthesization(expr, leftBegin, leftEnd, true, lookup)
* countParenthesization(expr, rightBegin, rightEnd, true, lookup);
count += countParenthesization(expr, leftBegin, leftEnd, false, lookup)
* countParenthesization(expr, rightBegin, rightEnd, false, lookup);
}
break;
}
}
lookup.put(lookupKey, count);
//System.out.println(lookup);
return count;
}