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]+" "); } } }
  • 相关阅读:
    python路径拼接os.path.join()函数的用法
    selenium常用定位方式
    谷歌浏览器发生个人资料错误
    【回顾】html属性、标题、段落、文本格式化
    【回顾】html简介、基础、元素
    类的定义与使用
    简单的超市库存管理系统
    方法定义练习
    参数传递
    方法的重载
  • 原文地址:https://www.cnblogs.com/loren-Yang/p/7536355.html
Copyright © 2011-2022 走看看