我指的是这个问题:Given a dictionary, i.e., a set of strings, and a string s, design an
efficient algorithm that checks whether s is the concatenation of a
sequence of dictionary words. If such a concatenation exists, your
algorithm should output it.
以下是我在不使用DP的情况下解决问题的方法:def getwords(s, start = 0):
# Find a valid word as a prefix, and try to made the rest work
for i in range(start + 1, len(s) + 1):
prefix = s[start:i]
if isind(prefix):
# We used the whole thing, but it's a word!
if i == len(s):
return [prefix]
words = getwords(s, i)
if words:
return [prefix] + words
# We made it to the end without finding a word configuration
return False
DP算法被记录在here,并在“编程元素访谈”一书中。我的问题是:为什么?
我找不到任何非DP解决方案重新计算相同子问题的实例。有人能解释为什么这个算法不如DP算法吗?在