求数组的最长递增子序列

/**
 * 采用动态规划找出数组的最长的递增子序列
 */
public class LongestSub {


    /**
     *
     * 从上面的分析中找到规律,即dp[i]的值是前面所有小于arr[i]的数组的dp[i]的最大值+1;
     */
    public static void main(String[] args) {
        int [] arr = {9,10,19,20,21,22,11,12,13,14,15};
        int len = arr.length;
        int [] dp = new int[len];
        Arrays.fill(dp , 1);//采用1填充数组 这时dp[0] = 1 了
        for(int i = 1; i < len; i++){
            int max = -1;
            for(int w = 0; w < i; w++){
                if(arr[w] < arr[i]){
                    max = Math.max(max,dp[w]);
                    dp[i] = max +1;
                }
            }
        }
        int length = dp[0];
        System.out.print("        原始数组为:");
        for(int k = 0; k < len; k++){
            System.out.print(arr[k] + " ");
        }
        System.out.println();
        System.out.print("递增子序列长度数组为:");
        for(int i = 0; i < len; i++){
            System.out.print(dp[i] + " ");
            if(length < dp[i]){
                length = dp[i];
            }
        }
        System.out.println();
        System.out.println("递增子序列的最大长度为: "+length);


        //打印最长的递增子序列
        List<Integer> list = new ArrayList<>();
        int m = len - 1;
        for(int q = length; q >= 1; q-- ){
            for(int k = m ; k >= 0; k--){
                if(dp[k] == q){
                    list.add(arr[k]);
                    m = k-1;
                    break;
                }
            }
        }
        for(int k = list.size() - 1; k >= 0; k--){
            System.out.print(list.get(k) + " ");
        }
    }
}

  

posted @ 2020-05-31 02:44  踏月而来  阅读(334)  评论(0编辑  收藏