待补充:
时间复杂度为O(nlogn)的方法
————————————————————————
我们先考虑时间复杂度为O(n^2)的方法
根据题目的特征,存在大量重叠问题
我们很容易想到使用动态规划
定义子问题为:
求以当前位置为末尾的最长上升子序列长度
如对[10,9,2,5,3,7,101,18]
以每个位置为末尾的最长上升子序列的长度为
[1,1,1,2,2,3,1,4]
那么dp[i]与前者的关系为:
我们称nums[0:i-1]这个子序列中包含的所有比nums[i]小的数字构成的序列为S
dp[i] = max(dp[j])+1,j∈S
最后,我们返回max(dp)
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
if nums == []:
return 0
dplist = []
length = len(nums)
for i in range(length):
if i == 0:
dplist.append((1))
#dplist中存放一个个数字,
#dplist[i]是以i位置为结尾的最长上升子序列的长度,
else:
tempmax = -1
tempindex = -1
for j in range(i):
if nums[j] < nums[i]:
if dplist[j] > tempmax:
tempmax = dplist[j]
tempindex = j
if tempindex == -1:#nums[0:i-1]中没有比nums[i]更小的
dplist.append(1)
else:
dplist.append(dplist[tempindex] + 1)
return max(dplist)