繁体   English   中英

子序列最长增加的问题-天真的方法

[英]Issues with Longest Increasing Subsequence - Naive Approach

我正在学习动态编程的基础知识,并提出了在数组中找到最长增长子序列的问题 在查找DP解决方案之前,我决定自己编写代码,并提出了以下算法,有关完整代码,请参见此处

想法是创建一个列表数组来存储所有递增的子序列,并存储每个子序列的相应最大值以进行更快的比较。

private void findLIS(int[] inputArr) {
    List[] listOfSubs = new ArrayList[inputArr.length];    //Max different subsequences in an array would be N
    //To store the max value of each of the subsequences found yet
    List<Integer> maxValList = new ArrayList<Integer>();
    listOfSubs[0] = new ArrayList<Integer>();
    listOfSubs[0].add(inputArr[0]);    //Add the first element of the array to the list
    maxValList.add(inputArr[0]);

    for (int i=1;i<inputArr.length;i++) {
        boolean flag = false;
        int iter=0;

        //Compare inputArr[i] with the maxVal of each subsequence
        for (int j=0; j<maxValList.size(); j++) {
            if (inputArr[i]>maxValList.get(j)) {
                maxValList.set(j, inputArr[i]); //Update the maxVal in the corresponding position in the list
                listOfSubs[j].add(inputArr[i]);
                flag = true;
            }
            iter = j;
        }
        //If inputArr[i] is not greater than any previous values add it to a new list
        if (!flag) {
            maxValList.add(inputArr[i]);
            listOfSubs[iter+1] = new ArrayList<Integer>();
            listOfSubs[iter+1].add(inputArr[i]);
        }
    }

    //Finding the maximum length subsequence among all the subsequences
    int max=0, iter=0, index=0;
    for (List<Integer> lst : listOfSubs) {
        if (lst!=null && lst.size() > max) {
            max = lst.size();
            index=iter;
        }
        iter++;
    }

    //Print the longest increasing subsequence found
    System.out.println("The Longest Increasing Subsequence is of length " + listOfSubs[index].size() +
            " and is as follows:");
    for (int i=0;i<listOfSubs[index].size();i++) {
        System.out.print(listOfSubs[index].get(i) + " ");
    }
}

该代码运行时间为O(n ^ 2),非常适合中小型输入。 但是,当我尝试在某些在线练习门户网站(例如HackerRank )上运行代码时,同时出现TLE(时间限制超出错误)和错误答案。 我理解TLE错误,因为有效的解决方案是DP O(nlogn)解决方案,但是我对该算法生成的错误答案感到困惑。 由于此类情况的输入过大(〜10000),因此我无法手动验证解决方案出了哪些问题。

完整的代码以及对数据集之一的输出可在此处找到。 正确答案应该是HackerRank报告的195。

我找到了解决方案的问题。 问题是由于未仔细阅读问题说明。

假设我们认为输入为{3,2,6,4,4,5,1}。 我只考虑代码中的序列{3,6}和{2,6},而不考虑序列{2,4,5}或{3,4,5}。 因此,在每次迭代中,如果我发现一个大于前一个子序列的最大值的数,则将其添加到所有此类子序列中,从而减少了到达后一个子序列的可能性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM