【发布时间】:2019-06-02 20:27:16
【问题描述】:
我正在解决 leetcode 上的this 问题。无法计算出我的解决方案的时间和空间复杂度。
特别是,如果我们有 FOR 循环,我不明白如何在这里应用Master Theorem。这里的 a 和 b 是什么?由于输入被多次划分并且针对不同大小的子问题。另一个复杂因素是记忆。
class Solution {
private Map<String, List<Integer>> cache = new HashMap<>();
public List<Integer> diffWaysToCompute(String equation) {
if (cache.containsKey(equation)) return cache.get(equation);
if (!(equation.contains("+") || equation.contains("-") || equation.contains("*"))) return Collections.singletonList(Integer.valueOf(equation));
List<Integer> result = new ArrayList<>();
for (int i = 0; i < equation.length();i++) {
char ch = equation.charAt(i);
if (ch == '+' || ch == '-' || ch == '*') {
List<Integer> left = diffWaysToCompute(equation.substring(0, i));
List<Integer> right = diffWaysToCompute(equation.substring(i+1, equation.length()));
result.addAll(crossCalc(left, right, ch));
}
}
cache.put(equation, result);
return result;
}
private List<Integer> crossCalc(List<Integer> left, List<Integer> rigth, char sign) {
List<Integer> result = new ArrayList<>();
for (Integer l : left) {
for (Integer r : rigth) {
if (sign == '-') {
result.add(l - r);
} else if (sign == '+') {
result.add(l + r);
} else {
result.add(l*r);
}
}
}
return result;
}
}
我正在寻找解释如何计算时间复杂度,而不仅仅是答案。如果你能解释有和没有记忆的复杂性,最好。谢谢!
【问题讨论】:
-
我不认为你可以在这里应用主定理。如果您将问题分成两个或多个完全不相交的子问题并在最后合并它们的结果,则使用主定理
标签: java algorithm recursion time-complexity divide-and-conquer