Skip to content

Commit 7b6cab8

Browse files
SherlockGuoLockyGuolabuladong
authored
【300.最长上升子序列】【Python】 (labuladong#507)
* add python * add python * add python Co-authored-by: LockyGuo <gh19920419@gmail.com> Co-authored-by: labuladong <labuladong@foxmail.com>
1 parent 424f210 commit 7b6cab8

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

动态规划系列/动态规划设计:最长递增子序列.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,51 @@ public int lengthOfLIS(int[] nums) {
217217

218218
======其他语言代码======
219219

220+
```python 动态规划
221+
class Solution:
222+
def lengthOfLIS(self, nums: List[int]) -> int:
223+
n = len(nums)
224+
f = [1] * (n)
225+
226+
for i in range(n):
227+
for j in range(i):
228+
if nums[j] < nums[i]:
229+
f[i] = max(f[i], f[j] + 1)
230+
231+
res = 0
232+
for i in range(n):
233+
res = max(res, f[i])
234+
return res
235+
```
236+
237+
```python 二分查找
238+
class Solution:
239+
def lengthOfLIS(self, nums: List[int]) -> int:
240+
stack = []
241+
242+
def find_index(num):
243+
l, r = 0, len(stack)
244+
while l < r:
245+
mid = l + r >> 1
246+
if stack[mid] >= num:
247+
r = mid
248+
else:
249+
l = mid + 1
250+
251+
return r
252+
253+
254+
for num in nums:
255+
if not stack or num > stack[-1]:
256+
stack.append(num)
257+
else:
258+
position = find_index(num)
259+
stack[position] = num
260+
261+
return len(stack)
262+
```
263+
264+
220265
[Kian](https://github.com/KianKw/) 提供 C++ 代码
221266

222267
```c++
@@ -257,3 +302,4 @@ public:
257302
}
258303
};
259304
```
305+

0 commit comments

Comments
 (0)