[DP]Longest Increasing Subsequence

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数组扫描,找到最大的那个。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值