zoukankan      html  css  js  c++  java
  • 最长递增子序列

    给定数组arr,返回arr最长递增子序列。

    举例:

    arr=[2, 1, 5, 3, 6, 4, 8, 9, 7],返回的最长递增子序列是[1,3,4,8,9]。

    方法:

    建立dp[i]数组,每一位表示以这一位结尾的最长递增子序列,然后根据最大值求出子序列。

    时间复杂度为O(n^2).

    代码:

    public class Main {
        
      //求出dp数组
    public static int[] getDP(int[] array) { if(array==null || array.length==0) { return null; } int len = array.length; int[] dp = new int[len]; for(int i=0; i<len; i++) { dp[i] = 1; for(int j=0; j<i; j++) { if(array[j] < array[i]) { dp[i] = Math.max(dp[j]+1, dp[i]); } } } return dp; }
      //根据dp数组中的最大值,反向求子序列
    public static int[] generateLIS(int[] dp, int[] array) { int max = 0; int index = 0; int len = dp.length; for(int i=0; i<len; i++) { if(dp[i] >max) { max = dp[i]; index = i; } } int[] res = new int[max]; res[--max] = array[index]; for(int j=index; j>=0; j--) { if(array[j] <array[index] && (dp[j]+1)==dp[index]) { res[--max] = array[j]; index = j; } } return res; } public static void main(String[] args) { int[] arr = { 2, 1, 5, 3, 6, 4, 8, 9, 7 }; int[] dp = getDP(arr); int[] res = generateLIS(dp,arr); for(int i=0; i<res.length; i++) { System.out.print(res[i]+" "); } } }
  • 相关阅读:
    bootstrap
    前端框架 angularjs
    JAva集合框架
    圣诞
    IDEA
    科目三
    Bootstrap简介及Bootstrap里的栅格系统col-md/sm/xs-x;
    C# Windows service 定时发邮件功能 (用到webService)
    <转> 数据库索引的作用和优点缺点
    小知识
  • 原文地址:https://www.cnblogs.com/loren-Yang/p/7536355.html
Copyright © 2011-2022 走看看