The longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order. For example, length of LIS for { 10, 22, 9, 33, 21, 50, 41, 60, 80 } is 6 and LIS is {10, 22, 33, 50, 60, 80}.
Optimal Substructure:
Let arr[0..n-1] be the input array and L(i) be the length of the LIS till index i such that arr[i] is part of LIS and arr[i] is the last element in LIS, then L(i) can be recursively written as.
L(i) = { 1 + Max ( L(j) ) } where j < i and arr[j] < arr[i] and if there is no such j then L(i) = 1
To get LIS of a given array, we need to return max(L(i)) where 0 < i < n
So the LIS problem has optimal substructure property as the main problem can be solved using solutions to subproblems.
#include <stdio.h>
#include <stdlib.h>
/* Longest Inceasing Subsequence */
unsigned int lis(int a[], unsigned int n)
{
unsigned int *lis;
unsigned int result, max;
int i,j;
if( n == 0 ) return 0;
if( n == 1 ) return 1;
lis = (unsigned int *)malloc(n * sizeof(unsigned int));
lis[0] = 1;
for( i = 1; i < n; i++)
{
lis[i] = 1;
for( j = 0; j < i; j++)
{
if(a[j] <= a[i] && lis[i] < lis[j]+1)
lis[i] = lis[j]+1;
}
}
// pick the max
max = lis[0];
for( i = 1; i < n; i++)
if(lis[i]>max)
max = lis[i];
result = max;
free(lis);
return result;
}
int main()
{
int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60, 2};
int n = sizeof(arr)/sizeof(arr[0]);
printf("Length of LIS is %d\n", lis( arr, n ) );
return 0;
}
自己解题的时候遇到的问题:最开始妄想用lis[i] 保存arr[1..i]的最长连续数列,但是实际操作的时候,写成这样:
for i <- 1 to n
current_max <- 1
for j <- 0 to i-1
if arr[j] <= arr[i] and current_max < c[i] +1
current_max <- c[i]+1
c[i] <- current_max
但是在返回结果的时候, 返回 c[n-1],这个时候 c[n-1] 可能变成1了。因此要再做最后一次对lis数组扫描,找到最大的那个。