这个C++函数与等效的java函数的工作方式有何不同?

Bas*_*tor 1 c++ java algorithm dynamic-programming

我正在尝试实现以下C++算法的Java版本:

void constructPrintLIS(int arr[], int n)
{
    std::vector< std::vector<int> > L(n);

    L[0].push_back(arr[0]);

    for (int i = 1; i < n; i++)
    {
        for (int j = 0; j < i; j++)
        {
            if ((arr[i] > arr[j]) &&
                (L[i].size() < L[j].size() + 1))
            {
                L[i] = L[j];
                cout << true << endl;
            }
            else
            {
                cout << false << endl;
            }
        }

        L[i].push_back(arr[i]);
    }

    std::vector<int> max = L[0];

    for (std::vector<int> x : L)
    {
        if (x.size() > max.size())
        {
            max = x;
        }
    }

    printLIS(max);
}
Run Code Online (Sandbox Code Playgroud)

这是Java版本

private static List<Integer> getLongestIncreasingSubsequence(
        List<Integer> sequence
        )
{   
    ArrayList<ArrayList<Integer>> cache = 
            new ArrayList<ArrayList<Integer>>(sequence.size());
    // Populate the elements to avoid a NullPointerException
    for(int i = 0; i < sequence.size(); i++)
    {
        cache.add(new ArrayList<Integer>());
    }
    cache.get(0).add(sequence.get(0));

    // start from the first index, since we just handled the 0th
    for(int i = 1; i < sequence.size(); i++)
    {
        // Add element if greater than tail of all existing subsequences
        for(int j = 0; j < i; j++)
        {
            if((sequence.get(i) > sequence.get(j)) 
                    && (cache.get(i).size() < cache.get(j).size() + 1))
            {
                cache.set(i, cache.get(j));
            }
        }
        cache.get(i).add(sequence.get(i));                  
    }

    // Find the longest subsequence stored in the cache and return it
    List<Integer> longestIncreasingSubsequence = cache.get(0);
    for(List<Integer> subsequence : cache)
    {
        if(subsequence.size() > longestIncreasingSubsequence.size())
        {
            longestIncreasingSubsequence = subsequence;
        }
    }
    return longestIncreasingSubsequence;
}
Run Code Online (Sandbox Code Playgroud)

我不明白我在做什么不同.C++算法在测试序列打印时输出正确的结果{9766, 5435, 624, 6880, 2660, 2069, 5547, 7027, 9636, 1487},结果正确624, 2069, 5547, 7027, 9636.但是,我编写的Java版本返回的结果不正确624, 6880, 2660, 2069, 5547, 7027, 9636, 1487,我不明白为什么.我试过在调试器中跟踪它,我无法弄清楚出了什么问题.

我尝试添加一个print语句,指示if语句每次都被评估为true/false,并将其与C++程序进行比较,并且它是相同的,所以这不是问题.

我怀疑它与vector和ArrayList之间的细微差别有关,但我不知道.

Hoo*_*pje 6

我怀疑问题是在Java中,缓存包含对列表的引用,而在C++中它包含列表本身.

因此,在C++中

L[i] = L[j];
Run Code Online (Sandbox Code Playgroud)

j将索引处的列表复制到索引i,而在Java中

cache.set(i, cache.get(j));
Run Code Online (Sandbox Code Playgroud)

复制参考.这意味着,当您随后向一个项目添加项目时,它们也会添加到另一个项目中.

也许用

cache.set(i, new ArrayList<>(cache.get(j)));
Run Code Online (Sandbox Code Playgroud)

这样你就可以像在C++中一样创建一个副本.

  • @Airhead`ArrayList(Collection)`是一个复制传入集合的构造函数. (2认同)