Update 0300.最长上升子序列.md

This commit is contained in:
jianghongcheng
2023-06-06 15:29:07 -05:00
committed by GitHub
parent 22615387a5
commit d3a07fa1bd

View File

@ -141,7 +141,7 @@ class Solution {
} }
} }
``` ```
DP
Python Python
```python ```python
class Solution: class Solution:
@ -157,7 +157,31 @@ class Solution:
result = max(result, dp[i]) #取长的子序列 result = max(result, dp[i]) #取长的子序列
return result return result
``` ```
贪心
```python
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
if len(nums) <= 1:
return len(nums)
tails = [nums[0]] # 存储递增子序列的尾部元素
for num in nums[1:]:
if num > tails[-1]:
tails.append(num) # 如果当前元素大于递增子序列的最后一个元素,直接加入到子序列末尾
else:
# 使用二分查找找到当前元素在递增子序列中的位置,并替换对应位置的元素
left, right = 0, len(tails) - 1
while left < right:
mid = (left + right) // 2
if tails[mid] < num:
left = mid + 1
else:
right = mid
tails[left] = num
return len(tails) # 返回递增子序列的长度
```
Go Go
```go ```go
// 动态规划求解 // 动态规划求解