最长递增子序列

来源:互联网 发布:c语言写的游戏 编辑:程序博客网 时间:2024/06/01 08:11
package algorithm;public class LongestIncreasingSubsequence {     void getLIS(int[] array){         /**          *max:最长递增序列元素个数          *maxIndex:最长递增序列中最后一个元素的下标          *preIndex:保存最长子序列各个元素,开始都指向自己          *LIS:用于记录当前各元素作为最大元素的最长递增序列长度,每个元素初始最大LIS是本身就是1          */         int i,j,max = 1,maxIndex = 0;         int[] preIndex = new int[array.length];         int[] LIS = new int[array.length];         for(i = 0; i < array.length; i++){             preIndex[i] = i;             LIS[i] = 1;         }         for(i = 1; i < array.length; i++){             //遍历元素i之前各个元素作为最大元素的最长递增序列长度,找出最大值             for(j = 0; j < i; j++){                 if(array[j] < array[i] && LIS[j] + 1 > LIS[i]){                     LIS[i] = LIS[j] + 1;                     preIndex[i] = j;                     if(LIS[i] > max){                         max = LIS[i];                         maxIndex = i;                     }                 }             }         }         //打印最长子序列         while(preIndex[maxIndex] != maxIndex){             System.out.print(array[maxIndex] + "-");             maxIndex = preIndex[maxIndex];         }         System.out.print(array[maxIndex]);         System.out.println("\n max = " + max);     }//全是数字字符串情况下,最大递增数字public static int maxInrementInteger(String str){        int[] lis = new int[str.length()];        int[] max = new int[str.length()];        int maxInteger = Integer.MIN_VALUE;        Arrays.fill(lis,1);        int k = 0;        for(int m : max){            max[k] = str.charAt(k) - '0';            if(max[k] > maxInteger){                maxInteger = max[k];            }            k++;        }        for(int i = 1; i < str.length(); i++){            for(int j = 0; j < i; j++){                if(str.charAt(i) > str.charAt(j) && lis[j] + 1 >= lis[i]){                    int nowNum = Integer.valueOf(String.valueOf(max[j]) + str.charAt(i));                    if(nowNum > max[i]) {                        max[i] = nowNum;                    }                    if(nowNum > maxInteger){                        maxInteger = nowNum;                    }                }            }        }        return maxInteger;    }    public static void main(String[] args){        int[] testArray = {35, 36, 39, 3, 15, 27, 6, 42};        new LongestIncreasingSubsequence().getLIS(testArray);    String str = "381294";    System.out.println(maxInrementInteger(str));    }}
0 0
原创粉丝点击