[模板题] - 300. 最长递增子序列
题目链接 | 300. 最长递增子序列 |
---|---|
思路 | 1. 动态规划 2. 贪心+二分 |
题解链接 | 【视频】三种方法:记忆化搜索/递推/二分查找(Python/Java/C++/Go) |
关键点 | 无 |
时间复杂度 | 动态规划:\(O(n^2)\) 贪心+二分:\(O(n\log n)\) |
空间复杂度 | 动态规划:\(O(n)\) 贪心+二分:\(O(n)\) |
代码实现(动态规划):
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
@cache
def dfs(i):
answer = 0
for j in range(i):
if nums[j] < nums[i]:
answer = max(answer, dfs(j))
return answer + 1
return max(dfs(i) for i in range(len(nums)))
代码实现(贪心+二分):
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
g = []
for x in nums:
j = bisect_left(g, x)
if j == len(g):
g.append(x)
else:
g[j] = x
return len(g)