zoukankan      html  css  js  c++  java
  • 【编程之美】2.16 求数组的最大递增子序列

    如 1  -1  2  -3  4  -5  6  -7的最大递增子序列为 1  2  4  6

    思路:动态规划 从后向前 存储下一个递增元素的位置 和以当前数字为首的递增子序列的长度

    答案中说可以用O(NlogN)我没看懂

    #include <stdio.h>
    #include<stdlib.h>
    
    //下面解法的时间复杂度 O(N^2)
    void getMaxAscendSubArray(int * a, int alen)
    {
        int * next = (int *)calloc(alen, sizeof(a[0])); //存储当前元素的下一个递增数字的下标
        int * count = (int *)calloc(alen, sizeof(a[0])); //存储以当前数字为首的子序列中 最大递增子序列的长度
    
        //动态规划 从后往前
        for(int i = alen - 1; i >= 0; i--)
        {
            next[i] = alen;
            count[i] = 1;
            for(int j = i + 1; j < alen; j++)
            {
                if(a[j] > a[i])
                {
                    next[i] = j;
                    count[i] += count[j];
                    break;
                }
            }
        }
    
        //找到长度最大的下标
        int max = 0;
        int maxid = 0;
        for(int i = 0; i < alen; i++)
        {
            if(count[i] > max)
            {
                max = count[i];
                maxid = i;
            }
        }
    
        //输出
        printf("
    ");
        printf("the input array is: ");
        for(int i = 0; i < alen; i++)
        {
            printf("%d ", a[i]);
        }
        printf("
    ");
        printf("the max increase sub array is: ");
        for(int i = maxid; i < alen;)
        {
            printf("%d ", a[i]);
            i = next[i];
        }
        printf("
    ");
        printf("the max increase sub array length is: %d
    ", max);
    }
    
    
    int main()
    {
        int a[8] = {1, -1, 2, -3, 4, -5, 6, -7};
        getMaxAscendSubArray(a, 8);
    
        return 0;
    }
  • 相关阅读:
    查找算法(I) 顺序查找 二分查找 索引查找
    快速排序 Quick Sort
    Activity生命周期
    Android中资源文件的使用
    排序算法
    插入排序(I)Insert Sort
    Java eclipse调试技巧什么的。。
    HTTP协议解析
    python技巧26[str+unicode+codecs]
    python类库26[PySide之helloworld]
  • 原文地址:https://www.cnblogs.com/dplearning/p/4092242.html
Copyright © 2011-2022 走看看