The task is to find the length of the longest subsequence in a given array of integers such that all elements of the subsequence are sorted in ascending order. For example, the length of the LIS for { 15, 27, 14, 38, 26, 55, 46, 65, 85 } is 6 and the longest increasing subsequence is {15, 27, 38, 55, 65, 85}.
O(n^2) time cost,O(n) space cost Solution
int LIS(int A[],int n){
int *L = (int *) malloc(n*sizeof(int));
int res = 1;
L[0]=1; //L[i] is the length of LIS that is end with A[i]
for(int i=1;i<n;i++){
int r = 0; //r is length of the longest increasing sub-seq
//whose last element is smaller than A[i]
for(int j=0;j<i;j++){
if(A[j]<A[i]) r = max(r,L[j]);
}
L[i] = r+1;
res = max(res,L[i]);
}
return res;
}
可以在内循环优化,维持一个动态数组 c[], c[i]表示长度为 i 的递增子序列的最小尾部值, 这样就有
c[1]<c[2]<...<c[L] ,注意是严格递增的,最后LIS的长度就是 L
O(n * log n) time cost, O(L) space cost
int LIS(int A[],int n){
vector<int> c; //c[i] = min{ 长度为i的上升序列的尾部值 }
c.push_back(INT_MIN);
for(int i=0;i<n;i++){
int k= lower_bound(c.begin(),c.end(),A[i]) - c.begin();
if(k==c.size()) c.push_back(A[i]); //找到更长的递增序列
else c[k]=A[i]; //更新c[k]
}
return c.size()-1;
}
Another Awesome Solution
算法复杂度与上一个相同,原来亦同,只不过是借助 C++ set
int LIS(int A[],int n){
set<int> tab;
pair<set<int>::iterator,bool> it;
for(int i=0;i<n;i++){
it = tab.insert(A[i]);
if(it.second==true && (++it.first)!=tab.end()) tab.erase(it.first);
}
return tab.size();
}