【发布时间】:2014-02-11 22:54:43
【问题描述】:
看了这篇Retiring a Great Interview Problem的文章,作者想出了一个work break的问题,给出了三个解决方案。高效的使用memoization算法,作者说它的最坏情况时间复杂度是O(n^2),因为the key insight is that SegmentString is only called on suffixes of the original input string, and that there are only O(n) suffixes。
但是,我很难理解为什么是O(n^2)。有人可以给我一个提示或证据吗?
Work Break Problem:
Given an input string and a dictionary of words,
segment the input string into a space-separated
sequence of dictionary words if possible. For
example, if the input string is "applepie" and
dictionary contains a standard set of English words,
then we would return the string "apple pie" as output.
记忆算法来自 Retiring a Great Interview Problem
Map<String, String> memoized;
String SegmentString(String input, Set<String> dict) {
if (dict.contains(input))
return input;
if (memoized.containsKey(input) {
return memoized.get(input);
}
int len = input.length();
for (int i = 1; i < len; i++) {
String prefix = input.substring(0, i);
if (dict.contains(prefix)) {
String suffix = input.substring(i, len);
String segSuffix = SegmentString(suffix, dict);
if (segSuffix != null) {
return prefix + " " + segSuffix;
}
}
}
memoized.put(input, null);
return null;
}
【问题讨论】:
-
解决方案不是最优的,它只在字符串输入的结果为空时更新memoized map,应该在所有情况下更新!
-
没错。请注意,
segSuffix仅在prefix位于dict中的单词中时才会被递归调用。如果该递归调用返回非null,则调用者也会立即返回,在堆栈上。换句话说,只要segSuffix调用返回一个不是null的值,算法就不会再调用segSuffix,所以不需要记住非null的值。 -
@Alp 很好,谢谢。在这种情况下,我猜只有一个布尔数组就足够了,因为我们总是可以将后缀作为它在整个输入字符串中的索引。
-
你们能帮我解释一下为什么是
O(n^2)吗?
标签: algorithm recursion time-complexity memoization