zoukankan      html  css  js  c++  java
  • 求数组最大递增子序列,并打印出该子序列

    /// 求最大递增子序列本身,输出路径,子序列不需要连续
    
    #include <bits/stdc++.h>
    
    using namespace std;
    
    int LIS(int *p, int length , int* pre, int& nindex);
    void GetLIS(int *p, int *pre, int nindex, vector<int>& lis);
    
    int main()
    {
        int a[] = {1,4,5,6,2,3,8,9};
        int size = 8;
        int *pre = new int[size];
        int nindex;
        int max = LIS(a, size, pre, nindex);
        cout << max << endl;
        vector<int> lis; // 保存最长递增子序列
        GetLIS(a, pre, nindex, lis);
        for (int li : lis) {
            cout << li << endl;
        }
        return 0;
    }
    
    int LIS(int *p, int length , int* pre, int& nindex)
    {
        // p原数组
        // length 原数组长度
        // pre 上升子序列的前一个元素的索引
        // nindex 记录最长上升子序列最后一个元素的索引
        int* longest = new int[length];  // 保存最大子串长度
        for(int i = 0; i < length; i++)
        {
            longest[i] = 1;
            pre[i] = -1;
        }
        int nlis = 1;  // 表示最大子串的最后一个字符位置,函数返回值, 以为longest要释放掉
        nindex = 0;
        for(int i = 1; i < length; i++)
        {
            for(int j = 0; j < i; j++)
            {
                if(p[j] <=  p[i])
                {
                    if(longest[i] < longest[j] +1)
                    {
                        longest[i] = longest[j] + 1;
                        pre[i] = j;
                    }
                }
            }
            if(nlis < longest[i])
            {
                nlis = longest[i];
                nindex = i;
            }
        }
        delete[] longest;
        return nlis;
    }
    
    void GetLIS(int *p, int *pre, int nindex, vector<int>& lis) {
        while(nindex >= 0)
        {
            lis.push_back(p[nindex]);
            nindex = pre[nindex];
        }
        reverse(lis.begin(),lis.end());
    }
    
    
    
  • 相关阅读:
    4:4 自定义拦截器
    DDD学习笔记一
    Winform/WPF国际化处理
    NPOI 操作Excel
    将输入的字符串进行大写格式化
    将输入的字符串分2个字符添加空格并大写格式化
    VS使用技巧
    NotifyIcon用法
    C#Winfrom系统打印机调用/设置默认打印机
    TextBox(只允许输入字母或者数字)——重写控件
  • 原文地址:https://www.cnblogs.com/myblog1993/p/11481063.html
Copyright © 2011-2022 走看看