classSolution(object): deflengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) if n == 0: return0 length = [1] * n for i in range(1, n): for j in range(i): if nums[i] > nums[j]: length[i] = max(length[j]+1, length[i]) return max(length)
classSolution(object): deffindNumberOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) if n == 0: return0 length = [1] * n count = [1] * n for i in range(1, n): for j in range(i): if nums[i] > nums[j]: if length[j] + 1 > length[i]: length[i] = length[j]+1 count[i] = count[j] elif length[j] + 1 == length[i]: length[i] = length[i] count[i] += count[j] max_len = max(length) res = 0 for i in range(n): if length[i] == max_len: res += count[i]
return res
拓展:二分法求解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# Dynamic programming + Dichotomy. classSolution: deflengthOfLIS(self, nums: [int]) -> int: tails, res = [0] * len(nums), 0 for num in nums: i, j = 0, res while i < j: m = (i + j) // 2 if tails[m] < num: i = m + 1# 如果要求非严格递增,将此行 '<' 改为 '<=' 即可。 else: j = m tails[i] = num if j == res: res += 1 return res