java - 使用递归找到所有可能的最长递增子序列

标签 java algorithm backtracking lis recursive-backtracking

我尝试使用递归找到所有可能的最长递增子序列。当我尝试输入数组 {10,22,9,33,21,50,41,40,60,55} 时,它起作用了,输出是:

10 22 33 40 55 /
10 22 33 41 55 /
10 22 33 50 55 /
10 22 33 40 60 /
10 22 33 41 60 /
10 22 33 50 60 /

但是当我尝试输入数组 {2,-3,4,90,-2,-1,-10,-9,-8} 时,我得到了一个输出:

-3 4 90 /
-3 -2 -1 /
-10 -9 -8 /

在这种情况下,我没有得到 2 4 90。我应该在我的代码中更改什么以使其符合这种情况?

public class Main {
    public static void main(String[] args) {
        int arr[]={10,22,9,33,21,50,41,40,60,55};
        int lis[]=new int[arr.length];
        for(int i=0;i<arr.length;i++){
            lis[i]=1;
        }
        for(int i=1;i<arr.length;i++){
            for(int j=0;j<i;j++){
                if(arr[i]>arr[j]&&lis[i]<lis[j]+1){
                    lis[i]=lis[j]+1;
                }
            }
        }
        int max=0;
        for(int i=0;i<arr.length;i++){
            if(max<lis[i])
                max=lis[i];
        }
        //**************Recursive Print LIS****************
        int rIndex=-1;
        for(int i=arr.length-1;i>=0;i--){
            if(lis[i]==max){
                 rIndex=i;
                 break;
            }
        }
        int res[]=new int[max];
        printLISRecursive(arr,rIndex,lis,res,max,max);
    }

    private static void printLISRecursive(int[] arr, int maxIndex, int[] lis, int[] res, int i, int max) {
        if(maxIndex<0)return;
        if(max==1&&lis[maxIndex]==1&&i==1){
            res[i-1]=arr[maxIndex];
//            System.out.println("Using Print Recursion:");
            for(int j=0;j<res.length;j++){
                System.out.print(res[j]+" ");
            }
            System.out.println();
            return;
        }
        if(lis[maxIndex]==max){
            res[i-1]=arr[maxIndex];
            printLISRecursive(arr, maxIndex-1, lis, res, i-1, max-1);
        }
        printLISRecursive(arr, maxIndex-1, lis, res, i, max);
    }

}

最佳答案

public static String  lcs(String  a, String  b){
    int aLen = a.length();
    int bLen = b.length();
    if(aLen == 0 || bLen == 0){
        return "";
    }else if(a.charAt(aLen-1) == b.charAt(bLen-1)){
        return lcs(a.substring(0,aLen-1),b.substring(0,bLen-1))
            + a.charAt(aLen-1);
    }else{
        String  x = lcs(a, b.substring(0,bLen-1));
        String  y = lcs(a.substring(0,aLen-1), b);
        return (x.length() > y.length()) ? x : y;
    }
}

关于java - 使用递归找到所有可能的最长递增子序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21796992/

相关文章:

algorithm - 推导子网定义的逆

c# - 匹配字符串之间有空格并连接具有重叠空格的模式

java - 输出中子串位移的回文分割问题的回溯解决方案

algorithm - 最小化矩阵中总线变化的数量

java - 哪里可以下载 Java 通信 API

java - 计算方差我得到无穷大

python - 二分查找递归错误: maximum recursion depth exceeded in comparison

python - 为所有节点创建具有相同入度和出度的矩阵

java - 与 volatile 'status flag' boolean 值同步?

java - 如何将按钮添加到 Canvas 而不让按钮调整大小?