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;
    }
    
  • 相关阅读:
    HDFS 常用Shell命令
    Hadoop单点伪分布模式安装
    部署及更新应用
    Linux云服务器下Tomcat部署超详细
    Android基础知识总结系列(一)——Android 系统框架
    Linux下的暴力密码在线破解工具Hydra安装及其组件安装-使用
    Luogu1501 Tree Ⅱ
    C#中Dictionary的用法(转)
    Lua协程
    SSH Secure Shell Client
  • 原文地址:https://www.cnblogs.com/chunzhulovefeiyue/p/8487481.html
Copyright © 2011-2022 走看看