数组中的最大递增子序列(Longest Increasing Subsequence)

给出一个数组,返回这个数组中的最大递增子序列:
例如:[1, 5, 6, 0, 7, 8, 3, 5], 则会返回LIS=[1, 5, 6, 7, 8]

import java.util.Arrays;
import java.util.Scanner;

public class LIS { // Longest Increasing Subsequence-->Time-complexity=O(n^2)
    public static int[] getLIS(int[] arr){
        int[] longest = new int[arr.length]; // longest[i](0<=i
        int[] prior = new int[arr.length]; // prior[i](0<=i
        for(int i = 0; i < arr.length; i++){
            longest[i] = 1;
            prior[i] = -1;
        }
        int indexOfMax = 0; // 当前LIS最大长度的位置索引
        int nLIS = 1; // 当前LIS最大长度
        for(int i = 0; i < arr.length; i++){
            for(int ii = 0; ii < i; ii++){
                if(arr[i] >= arr[ii]){ // arr[i]能够成为以arr[ii]结尾的LIS
                    if((longest[ii]+1) > longest[i]){
                        longest[i] = longest[ii] + 1;
                        prior[i] = ii;
                    }
                }
            }
            if(longest[i] > nLIS){
                indexOfMax = i;
                nLIS = longest[i];
            }
        }
        int[] LIS = new int[nLIS];
        for(int i = LIS.length - 1; ; i--){
            LIS[i] = arr[indexOfMax];
            indexOfMax = prior[indexOfMax];
            if(indexOfMax == -1){
                break;
            }
        }
        return LIS;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("(nums)> ");
        int nums = sc.nextInt();
        int[] arr = new int[nums];
        System.out.print("> ");
        for(int i = 0; i < nums; i++){
            arr[i] = sc.nextInt();
        }
        System.out.println(Arrays.toString(getLIS(arr)));
        sc.close();
    }
}

你可能感兴趣的:(剑指Offer)