rosalind练习题二十四

# Problem

# A subsequence of a permutation is a collection of elements of the permutation in the order that they appear. For example, (5, 3, 4) is a subsequence of (5, 1, 3, 4, 2).

# A subsequence is increasing if the elements of the subsequence increase, and decreasing if the elements decrease. For example, given the permutation (8, 2, 1, 6, 5, 7, 4, 3, 9), an increasing subsequence is (2, 6, 7, 9), and a decreasing subsequence is (8, 6, 5, 4, 3). You may verify that these two subsequences are as long as possible.

# Given: A positive integer n≤10000 followed by a permutation π of length n.

# Return: A longest increasing subsequence of π, followed by a longest decreasing subsequence of π.

# Sample Dataset

# 5

# 5 1 4 2 3

# Sample Output

# 1 2 3

# 5 4 2

# 对于一个给定的长度为 n 的排列 π,求它的最长上升子序列和最长下降子序列。

n =5

a = [5, 1, 4, 2, 3]

dp1 = [1] * n# 最长上升子序列

pre1 = [-1] * n# 记录前驱,方便输出

for iin range(n):

for jin range(i):

if a[j] < a[i]:

if dp1[j] +1 > dp1[i]:

dp1[i] = dp1[j] +1

                pre1[i] = j

dp2 = [1] * n# 最长下降子序列

pre2 = [-1] * n

for iin range(n):

for jin range(i):

if a[j] > a[i]:

if dp2[j] +1 > dp2[i]:

dp2[i] = dp2[j] +1

                pre2[i] = j

# 输出最长上升子序列

idx1 = dp1.index(max(dp1))

ans1 = []

while idx1 != -1:

ans1.append(a[idx1])

idx1 = pre1[idx1]

print(*ans1[::-1])# 注意倒序输出

# 输出最长下降子序列

idx2 = dp2.index(max(dp2))

ans2 = []

while idx2 != -1:

ans2.append(a[idx2])

idx2 = pre2[idx2]

print(*ans2[::-1])

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 设原始数据规模为n,需要采样的数量为k 先选取数据流中的前k个元素,保存在集合A中; 从第j(k + 1 <= j...
    Impossible安徒生阅读 2,472评论 0 0
  • 思路总结 数组: 数组内顺序: 是否有序? 如果排序,是否会有额外的性质? 递增、递减在该题内的含义? prefi...
    童言铜盐阅读 4,966评论 0 0
  • 动态规划常见问题 零、组合问题 1、硬币问题 n=len(arr) if n<=0 or aim<=0: ...
    是黄小胖呀阅读 1,661评论 0 0
  • 动态规划 [TOC] 单串问题 5.最长回文子串[https://leetcode-cn.com/problems...
    SwiftGo阅读 1,706评论 0 0
  • 各校历年复试机试试题 清华、北大、华科试题详细笔记部分,少笔记部分与少数leetcode【含个人整理笔记】 一、详...
    AIM外星人阅读 5,004评论 0 1

友情链接更多精彩内容