Longest common subsequence and longest increment sub-sequence

Source: Internet
Author: User

1. The longest common subsequence: (x and Y are the lengths of two arrays)

f (x, Y) = 0 if (x==0 | | y==0)

F (x-1,y-1) +1 if (a[x-1]==b[y-1])

Max{f (X-1,y), F (x,y-1)} if (A[x-1]!=b[y-1])

2, the longest increment sub-sequence

(1) The longest common subsequence method: the longest common subsequence of the original array after sorting.

(2) Dynamic programming Method: (Time complexity O (n^2))

An array of length n is {a0,a1, A2, ... an-1), then L (j) ={max{1,l (i) +1}, I<j and A[i]<a[j]} are assumed to be the longest increment subsequence length of an array sequence ending in AJ. That is, we need to traverse all positions before J (from 0 to j-1), find the L (i) that satisfies the condition a[i]<a[j], and calculate the value of Max (L (i)) +1, which is L (j). Finally, we traverse all the L (j) (from 0 to N-1) and find out the maximum is the maximum increment subsequence. The time complexity is O (n^2).
For example, the given array is {5,6,7,1,2,8}, then L (0) =1, L (1) =2, L (2) =3, L (3) =1, L (4) =2, L (5) = 4. So the longest increment of the array is the length of the subsequence 4, and the sequence is {5,6,7,8}. The algorithm code is as follows:

int lis (int arr[], int len)
{ intLongest[len];
for(intj =1; J < Len; J + +) {
Longest[i] = 1; for(inti =0; I < J; i++) { if(Arr[j] > Arr[i] && longest[j] < Longest[i] +1) {Longest[j]= Longest[i] +1; } } } intMax =0; for(inti =0; i < Len; i++) { if(Longest[i] >max) Max=Longest[i]; } returnMax;}

(3)

Longest common subsequence and longest increment sub-sequence

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.