子序列问题(最长连续子序列和最长递增子序列--Dynamic programming(三))

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_15642411/article/details/86847920

最长连续子序列个数

1)创建一个空的哈希表
2)插入元素到哈希表
3)遍历每个元素
检查元素是否子序列的起点。为了检查,我们可以简单在哈希表寻找arr[i]-1,如果找到,则arr[i]则是子序列的起点,否则步进。
计数连续的元素并更新count

Input: arr[] = {1, 9, 3, 10, 4, 20, 2};
Output: 4
1, 3, 4, 2 是最长的连续子序列(连续的次序是任意的)

#include <iostream>
#include <bits/stdc++.h>//万能头文件
using namespace std;
//寻找连续子序列,时间复杂度o(n)
int findLongestConseqSubseq(int arr[], int n)
{
    unordered_set<int> S;

    int ans = 0;
    for (int i = 0; i < n; i++)
        S.insert(arr[i]);
    for (int i=0; i<n; i++)
    {
        if (S.find(arr[i]-1) == S.end())
        {
            int j = arr[i];
            while (S.find(j) != S.end())
                j++;
            ans = max(ans, j - arr[i]);
        }
    }
    return ans;
}

最长递增子序列个数

Input : arr[] = {3, 10, 2, 1, 20}
Output : Length of LIS = 3
最长递增子序列是:3, 10, 20

//寻找递增子序列,时间复杂度o(n*n)
int LongIcreasingSquence(int arr[],int n)
{
    int lis[n];
    lis[0]=1;
    for(int i=1;i<n;++i)
    {
        lis[i]=1;
        for(int j=0;j<i;++j)
        {
            if(arr[i]>arr[j] && lis[i]<lis[j]+1)
            {
                lis[i]=lis[j]+1;
            }
        }
    }
    return *max_element(lis,lis+n);
}

猜你喜欢

转载自blog.csdn.net/qq_15642411/article/details/86847920