简体   繁体   English

不同长度数组中的公共子序列

[英]Common Subsequence in Different Length Arrays

I've implemented a DP algorithm that finds the longest common subsequence in three arrays. 我已经实现了一种DP算法,该算法可以找到三个数组中最长的公共子序列。 The problem though, is that my algorithm doesn't work when the arrays are of different lengths, and I have no idea why. 但是问题是,当数组的长度不同时,我的算法不起作用,我也不知道为什么。 From what I can tell, my algorithm is correct, so I think it's something to do with the Java implementation. 据我所知,我的算法是正确的,所以我认为这与Java实现有关。 Here is my Java code: 这是我的Java代码:

static int[] lcsOf3(int[] X, int[] Y, int[] Z, int xLength, int yLength, int zLength) {
        int[][][] S = new int[xLength + 1][yLength + 1][zLength + 1];

        for (int i = 0; i <= xLength; i++) {
            for (int j = 0; j <= yLength; j++) {
                for (int k = 0; k <= zLength; k++) {
                    if (i == 0 || j == 0 || k == 0) {
                        S[i][j][k] = 0;
                    } else if (X[i - 1] == Y[j - 1] && X[i - 1] == Z[k - 1]) {
                        S[i][j][k]= S[i - 1][j - 1][k - 1] + 1;
                    } else {
                        S[i][j][k] = Math.max(Math.max(S[i - 1][j][k], S[i][j - 1][k]), S[i][j][k - 1]);
                    }
                }
            }
        }
        System.out.println(S[xLength][yLength][zLength]);
}

I took another look at my code,and it turns out that it was something with my implementation, not the algorithm itself. 我再次看了一下我的代码,结果发现这与我的实现有关,而不是算法本身。 There was a bug in the part of my code that gets the input arrays(X,Y,Z). 我的代码部分存在一个错误,该错误获取输入数组(X,Y,Z)。 After fixing the bug, it works correctly on lists of different sizes. 修复错误后,它可以在不同大小的列表上正常工作。

Thanks to everyone who tried to help out, and sorry for wasting your time. 感谢所有尝试提供帮助的人,对于浪费您的时间深表歉意。

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

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