您的位置:首页 > 产品设计 > UI/UE

Longest Increasing Subsequence Review

2016-04-30 20:42 363 查看
LetA[1...n]beasequenceofdistinctintegers.Anincreasingsubsequence(IS)ofAisasubsequenceA[i1],A[i2],...,A[ik],withi1<i2<...<ik,suchthat,foris<it,wehaveA[is]<A[it].Alongestincreasingsubsequence(LIS)ofAisanincreasingsubsequenceofmaximumlength.

Problem:FindthelengthofLISofA

Westartwithasolutionusingdynamicprogramming.

letF[i]bethelengthofLISofA[1...i].
letG[i]bethemaximumlengthofISendingwithA[i].

Thenwehavethefollowingstate-transitionequations:

G[i]=max{G[j]+1}forall1<=j<iwithA[i]>A[j]
or1ifsuchajdoesnotexist

F[i]=max{G[j]}forall1<=j<=i

ItisobviousthattherunningtimeofthisalgorithmisO(n^2).

Canwedobetter?Definitely!

LetB[i]bethelastelementofaminimumLISoflengthi.AminimumLISoflengthiherereferstoaLISwhichhassmallestendingelementamongallLISesoflengthi.

WehaveB[i]<B[i+1]forall1<=i<n.(proofbycontradiction)

//initializeB
forifrom1ton
B[i]=nil

//calculateB
forifrom1ton
ifthere'ssuchajwith1<=j<i-1andB[j]<A[i]<B[j+1]
B[j+1]=A[i]
elseifA[i]<B[1]
B[1]=A[i]
elseifA[i]>B[i-1]
B[i]=A[i]

//findtheanswer
len=1
forifromndownto1
ifB[i]isnotnil
len=i
break

//thenlenholdsthelengthofLISofA.

Usingthisalgorithm,wecanfindthelengthofLISofAinrunningtimeofO(nlgn).

Discussion


WhatifAhasduplicateelements?


Thetwoalgorithmsabovearealsocorrectforsolvingthiscase.


Whatifwewanttofindthelengthoflongestnon-decreasingsubsequenceofasequencewhichmayhaveduplicateelements?


Itistrivaltomodifythefirstalgorithmtosolvethisproblem,weonlyneedtochangetransitionequationofG[i]to:

G[i]=max{G[j]+1}forall1<=j<iwithA[i]>=A[j]
or1ifsuchajdoesnotexist

Forthesecondalgorithm,wehavepropertyB[i]<=B[i+1]insteadofB[i]<B[i+1]inthiscase.AndthecalculatingprocessofBshouldbemodified.

//calculateB
forifrom1ton
ifthere'ssuchajwith1<=j<i-1andB[j]<=A[i]<B[j+1]
B[j+1]=A[i]
elseifA[i]<B[1]
B[1]=A[i]
elseifA[i]>=B[i-1]
B[i]=A[i]


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐
章节导航