LIS

来源:互联网 发布:可以在特定区域对网络 编辑:程序博客网 时间:2024/05/01 16:02

Code to find the Longest Increasing Subsequence of an array. Not the length but output the numbers.

动态规划思想:

数组:int a[];

a[i]应该接在a[0]...a[i-1]中1.小于a[i]的且b[i]最大的。


int b[]用来记录数组长度.

ANSWER:

Method1:

package com.zhuyu_deng.test;public class Test{static int a[] = new int[] { 7,7,7 };static int index[] = new int[a.length];public static void main(String args[]){int b[] = new int[a.length];for (int i = 1; i < a.length; ++i){b[i] = 1;for (int j = 0; j < i; ++j){if (a[j] < a[i] && b[j] + 1 > b[i]){b[i] = b[j] + 1;index[i] = j;}}}int max = 1;int maxIndex = 0;for (int i = 0; i < a.length; ++i){if (max < b[i]){max = b[i];maxIndex = i;}}print(maxIndex);}private static void print(int x){if (x != 0){print(index[x]);System.out.print(a[x] + " ");} else{System.out.print(a[x] + " ");}}}

Method2:

There is another way to find LIS, similar to patient sort, where you keep piles (stacks) to keep the increasing sequences.

By using this method, you can not only print the longest increasing sequence, but also print all the longest subsequences, if there are more than one maximum subsequence.



Method3:

There is another clean and neat DP solution based on DAG.

原创粉丝点击