动态编程的最大增加子序列

时间:2011-02-03 16:37:18

标签: algorithm dynamic-programming

问题如下: 给定n个整数的序列L不一定是不同的,写一个算法来计算最大长度的增加子序列:

我开发的递推方程是这样的:

我从0开始索引:

If j = n opt(j) = 0 (base case)
otherwise opt(j) = max j <i <= n such that Lj <Li = {opt(i) +1}
你觉得这样做是对的吗?用于这个典型问题的标准解决方案是首先计算序列中所有元素以Li结尾的最大增加子序列,然后计算这些值的最大值,即:

if i = 1 opt (i) = 1
otherwise opt (i) = max 1 <= j <= i-1 and Lj <Li = {opt (i)} +1

然后是这些元素的最大值。

所以我想知道你是否认为我的解决方案是正确的。

2 个答案:

答案 0 :(得分:1)

这里有一个提示:试图在算法中保留的循环不变量是变量,k =最长增长子序列开始的索引。因此,当您遍历整数序列[0 ... n]时,相应地增加k值。

答案 1 :(得分:0)

//给定一个整数数组,找到Longest Increase Subsequence的长度并打印序列。

int longsub (int a[], int len) {

    int localsum = 0;
    int i = 0;
    int begin = i;
    int localsublen = 1;
    int globalsunlen = 0;
    int end = i;

    for (i=1; i< len; i++)    {

        if (a[i] > a[i-1]) {
              localsublen++;
        }
        else {
            newbegin = i;
            localsublen = 1;
        }

        if (localsublen > globalsublen)    {
            begin = newbegin;
            end = i;
            globalsublen = localsublen;
        }
    }

    for (i=begin;i <= end; i++)    
        printf ("%d.\n",a[i]);


}
相关问题