leetcode 72.最长上升子序列

leetcode 300.673.最长上升子序列 DP问题
参考:https://github.com/labuladong/fucking-algorithm
讲得非常棒!


求最长上升子序列长度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution(object):
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n == 0:
return 0
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)

求最长上升子序列长度个数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution(object):
def findNumberOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n == 0:
return 0
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.
class Solution:
def lengthOfLIS(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

作者:jyd
链接:https://leetcode-cn.com/problems/longest-increasing-subsequence/solution/zui-chang-shang-sheng-zi-xu-lie-dong-tai-gui-hua-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×