提供两种解法。
第一种是正常的动态规则:
LIS是一个数组,里面维护的是每个位置最长上升子序列的值。在遍历数组的过程中,对应位置的LIS[i]都会得到更新,时间复杂度为O(n^2)
。
def lengthOfLIS(nums):
if not nums: return 0
LIS = [1] * len(nums)
for i in range(1, len(nums)):
for j in range(i):
if nums[i] > nums[j] and LIS[i] < LIS[j] + 1:
LIS[i] = LIS[j] + 1
return max(LIS)
print(lengthOfLIS(list(map(int, input().split()))))
也可以使用bisect模块,可以调试一下,观察每一步的变化:
import bisect
def lengthOfLIS(nums):
q=[]
for v in nums:
pos=bisect.bisect_left(q,v)
if pos==len(q):
q.append(v)
else:
q[pos]=v
return len(q)
print(lengthOfLIS(map(int,input().split())))