zoukankan      html  css  js  c++  java
  • Longest Increasing Subsequence

    Longest Incresing Subsequence(LIS)

    Category : Dynamic Programming(DP)

    Description : The Longest Increasing Subsequence (LIS) problem is to find the length of longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order. For Example, as shown by the picture.

    More Examples

    Input : arr[] = {3, 10, 2, 1, 20}
    Output : Length of LIS = 3
    The longest increasing subsequence is 3, 10 ,20
    
    Input : arr[] = {3, 2}
    Output : Length of LIS = 1
    The longest increasing subsequence is {3} and {2}
    
    Input : arr[] = {50, 3, 10, 7, 40, 80}
    Output : Length of LIS = 4
    The longest increasing subsequence is {3, 7, 40 ,80}
    

    Optimal Substructrue

    1. Let arr[0..n-1] be the input array and L(i) be the length of the LIS ending at index i such that arr[i] is the last element of the LIS

    2. Then, L(i) can be recursively written as:

      • L(i) = 1 + max( L(j) ) where 0 < j < i and arr[j] < arr[i]

        or

      • L(i) = 1, if no such j exists

    3. To find the LIS for a given array, we need to return max(L(i)) where 0 < i < n

    Code

    int lis(int arr[], int n)
    {
        int *lis, i, j, max = 0;
        lis = (int *)malloc(sizeof (int ) * n);
        
        /* init */
        for(i = 0; i < n; i++)
        {
            lis[i] = 1;
        }
        
        /* Compute optimized LIS values in bottom up manner */
        for(i = 1; i < n; i++)
        {
            for(j = 0; j < i; j++)
            {
    			if(arr[i] > arr[j] && lis[i] < lis[j] + 1)
                    lis[i] = lis[j] + 1;
            }
        }
        for (i = 0; i < n; i++)
        {
            if (max < lis[i])
                max = lis[i];
        }
        
        free(lis);
        
        return max;
    }
    
    /* Driver program to test above function */
    int main()
    {
        int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
        int n = sizeof(arr)/sizeof(arr[0]);
        printf("Length of lis is %dn", lis( arr, n ) );
        return 0;
    }
    
  • 相关阅读:
    window安装php的mongodb扩展
    Android NDK开发步骤(r9)
    osgViewer销毁bug
    C/C++ typedef用法
    Java并发编程:Lock
    java中构造器(Constructor)
    进程和线程关系及区别
    Java总结篇系列:Java泛型
    在powerdesigner中创建物理数据模型
    非常好的理解遗传算法的例子
  • 原文地址:https://www.cnblogs.com/chunzhulovefeiyue/p/8487481.html
Copyright © 2011-2022 走看看