rosalind練習(xí)題二十四

# 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# 記錄前驅(qū),方便輸出

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])

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 設(shè)原始數(shù)據(jù)規(guī)模為n,需要采樣的數(shù)量為k 先選取數(shù)據(jù)流中的前k個元素,保存在集合A中; 從第j(k + 1 <= j...
    Impossible安徒生閱讀 335評論 0 0
  • 思路總結(jié) 數(shù)組: 數(shù)組內(nèi)順序: 是否有序? 如果排序,是否會有額外的性質(zhì)? 遞增、遞減在該題內(nèi)的含義? prefi...
    童言銅鹽閱讀 1,303評論 0 0
  • 動態(tài)規(guī)劃常見問題 零、組合問題 1、硬幣問題 n=len(arr) if n<=0 or aim<=0: ...
    是黃小胖呀閱讀 260評論 0 0
  • 動態(tài)規(guī)劃 [TOC] 單串問題 5.最長回文子串[https://leetcode-cn.com/problems...
    SwiftGo閱讀 267評論 0 0
  • 各校歷年復(fù)試機試試題 清華、北大、華科試題詳細筆記部分,少筆記部分與少數(shù)leetcode【含個人整理筆記】 一、詳...
    AIM外星人閱讀 1,321評論 0 1

友情鏈接更多精彩內(nèi)容