【发布时间】:2015-08-19 22:21:49
【问题描述】:
我指的是这个问题:
给定一个字典,即一组字符串和一个字符串 s,设计一个 检查 s 是否是 a 的串联的有效算法 字典单词的序列。如果存在这样的串联,您的 算法应该输出它。
这是我在不使用 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算法?
【问题讨论】:
标签: python dynamic-programming