The longest increasing subsequence (LIS)
Given a sequence, find the longest subsequence of the sequence so that all the elements of the subsequence are ascending, and the relative positions between the elements are constant (the elements can be nonadjacent in the original array, but the relative position remains the same)
For example, LIS for {10, 22, 9, 33, 21, 50, 41, 60, 80} are 6,lis {10, 22, 33, 50, 60, 80}.
Analysis
ARR[0...N-1] is the input, then L (i) is the length of the LIS to the element I, that is, Arr[i] as the last element of the LIS when the length of the LIS, then with the recursive form L (i) can be written:
for (j<i) if (Arr[j]<arr[i]) L (i) = {1+if// recursive termination condition L (i) = 1
So this problem can be broken down into subproblems and solved by recursion:
#include <iostream>using namespacestd;intLIS (int*arr,intNint*max_ref) { if(n==1)return 1; intRes, longest_here=1; for(inti =1; i<n; ++i) {res=LIS (arr, I, max_ref); if(arr[i-1]<arr[n-1] && res+1>longest_here) Longest_here= res+1; } if(*max_ref <longest_here)*max_ref =Longest_here; returnLongest_here;}intMain () {intArr[] = {Ten, A,9, -, +, -, A, - }; intn =sizeof(arr)/sizeof(arr[0]); intmax=1; LIS (arr, N,&max); cout<<max<<Endl; return 0;}
Non-recursive method, this need to open up additional storage space.
intLIS2 (int*arr,intN) { int*longest_here =New int[n] (); longest_here[0] =1; intMax =1; for(inti =1; i<n; ++i) { for(intj =0; j<i; ++j) {if(Arr[j]<arr[i] && longest_here[j]+1>Longest_here[i]) longest_here[i]= longest_here[j]+1; } if(longest_here[i]>max) Max=Longest_here[i]; } Delete[]longest_here; returnMax;}
A solution with Time complexity O (Nlog (n)) at the top of the wiki
The longest ascending subsequence in the array (Dynamic planning problem)