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

# 對(duì)于一個(gè)給定的長(zhǎng)度為 n 的排列 π,求它的最長(zhǎng)上升子序列和最長(zhǎng)下降子序列。

n =5

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

dp1 = [1] * n# 最長(zhǎng)上升子序列

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# 最長(zhǎng)下降子序列

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

# 輸出最長(zhǎng)上升子序列

idx1 = dp1.index(max(dp1))

ans1 = []

while idx1 != -1:

ans1.append(a[idx1])

idx1 = pre1[idx1]

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

# 輸出最長(zhǎng)下降子序列

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)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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

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