【发布时间】:2013-04-13 19:10:38
【问题描述】:
我刚刚编写了这个实现来使用动态编程找出longest increasing subsequence 的长度。因此,对于输入为 [10, 22, 9, 33, 21, 50, 41, 60, 80],LIS 为 6,其中一组为 [10, 22, 33, 50, 60, 80]。
当我运行以下代码时,我得到的正确答案为 6,复杂度为 O(n)。这是正确的吗?
def lis(a):
dp_lis = []
curr_index = 0
prev_index = 0
for i in range(len(a)):
prev_index = curr_index
curr_index = i
print 'if: %d < %d and %d < %d' % (prev_index, curr_index, a[prev_index], a[curr_index])
if prev_index < curr_index and a[prev_index] < a[curr_index]:
print '\tadd ELEMENT: ', a[curr_index]
new_lis = 1 + max(dp_lis)
dp_lis.append(new_lis)
else:
print '\telse ELEMENT: ', a[curr_index]
dp_lis.append(1)
print "DP LIST: ", dp_lis
return max(dp_lis)
if __name__ == '__main__':
a = [10, 22, 9, 33, 21, 50, 41, 60, 80]
print lis(a)
【问题讨论】:
-
[10, 100, 20, 30, 40, 50, 60, 70, 80] 会发生什么?
-
它正确地说 LIS 的长度为 8,这是正确的
[10,20,30,40,50,60,70,80] -
max(dp_lis)是否适用于 O(1) 复杂度? -
在 python 中
max需要O(n)时间。我到处读到最长增加子序列需要O(n^2),优化版本需要O(nlogn),但我上面的实现是在O(n)时间完成的。我错过了什么? -
我试过
[10, 100, 200, 30, 40, 50, 60, 70, 80],它错误地说LIS的长度是8,应该是7[10, 30, 40, 50, 60, 70, 80]
标签: python algorithm dynamic-programming