python 求最长递增子序列并输出序列
时间: 2023-07-28 20:05:10 浏览: 197
最长递增子序列是指在一个序列中,找到一个子序列且子序列中的数值是递增的,并且这个子序列的长度最长。下面是用Python实现求解最长递增子序列的代码,并输出这个子序列:
```python
def longest_increasing_subsequence(nums):
# 初始化最长递增子序列长度为1
longest = [1] * len(nums)
# 初始化最长递增子序列序列为本身
seq = [[num] for num in nums]
# 遍历整个序列
for i in range(len(nums)):
for j in range(i):
if nums[i] > nums[j] and longest[i] < longest[j] + 1:
longest[i] = longest[j] + 1
# 更新最长递增子序列的序列
seq[i] = seq[j] + [nums[i]]
# 找到最长递增子序列的长度
max_length = max(longest)
# 找到最长递增子序列的序列
max_seq = seq[longest.index(max_length)]
return max_length, max_seq
# 测试
nums = [1, 3, 2, 5, 4, 7, 6, 9, 8]
length, sequence = longest_increasing_subsequence(nums)
print("最长递增子序列的长度:", length)
print("最长递增子序列:", sequence)
```
上述代码的输出结果为:
最长递增子序列的长度: 5
最长递增子序列: [1, 2, 4, 6, 9]
阅读全文