我剛剛寫了這個實現來找出使用動態編程的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] ? – johnchen902 2013-04-20 13:25:14
它正確地說LIS的長度是8,這是正確的[10,20,30,40,50,60,70,80] – 2013-04-20 13:28:38
'max(dp_lis)'工作在O(1)複雜性中嗎? – johnchen902 2013-04-20 13:34:15