【发布时间】:2016-05-08 05:20:45
【问题描述】:
This是一个经典的算法问题。
DP 解确实是 n^3。
我在下面使用带有记忆的递归。
我需要详细解释一下下面代码的运行时间是什么?我对目前的答案不满意。有人可以帮忙吗?
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;
}
【问题讨论】:
-
我对当前的答案不满意。有人能帮忙详细说明一下上面代码的运行时间是什么吗?
标签: algorithm recursion runtime memoization boolean-expression