最长递增子序列

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值