【发布时间】:2014-12-05 21:09:05
【问题描述】:
谁能告诉我为什么这段代码不会产生每个递增的子序列?
我使用动态编程来解决这个问题,但我不知道为什么这段代码会失败。
参数A是一个整数序列。
def LIS(A):
# make a list of lists
L = list()
for i in range(0, len(A)):
L.append(list())
#the first increasing subsequence is the first element in A
L[0].append(A[0])
for i in range(1, len(A)):
for j in (0, i):
# a new larger increasing subsequence found
if (A[j] < A[i]) and ( len(L[i]) < len(L[j]) ):
L[i] = L[j]
L[i].append(A[i])
# print an increasing subsequence
print L[i]
此算法为 A = [3, 5, 10, 0, 1, 100, 2, 4, 7] 生成的示例输出:
[3, 5]
[3, 5, 10]
[0]
[1]
[3, 5, 10, 100]
[2]
[3, 5, 10, 100, 4]
[3, 5, 10, 100, 4, 7]
None
正确的输出:
[3]
[3, 5]
[3, 5, 10]
[0]
[0, 1]
[3, 5, 10, 100]
[0, 1, 2]
[0, 1, 2, 4]
[0, 1, 2, 4, 7]
【问题讨论】:
-
为什么
[0, 1, 100]无效? -
无论您在内部循环中尝试做什么都不起作用,因为您总是将
A的第一项与A[i]或A[i]与自身进行比较 -(0,1)不是在for j in (0, i):中迭代的正确内容。我没有看到您使用dynamic programming的任何证据。 -
放入一些打印语句以查看发生了什么 - 使用
pprint.pprint(L)作为函数中的最后一个语句,之后外部循环已停止. -
@wwii 这是LIS问题的动态规划解决方案。
-
我在 C++ 中实现了完全相同的东西并且工作正常。奇怪的 Python。
标签: python dynamic-programming