[DP题解] 最长递增子序列问题
[问题] 最长递增子序列
给出长度为N的数组,找出这个数组的最长递增子序列。
子序列的元素是递增的。
举例: 5 7 1 8 3 5 7 9, 最长递增子序列是 1 3 5 7 9
输入样例:
2
8
5 7 1 8 3 5 7 9
9
2 1 5 3 6 4 8 9 7
输出结果:
5
5
[算法分析]
[算法设计]
package com.bean.algorithmexec;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class LICSDP {
/*
* 最长递增子序列
* 给出长度为N的数组,找出这个数组的最长递增子序列。
* 子序列的元素是递增的。
* 举例: 5 7 1 8 3 5 7 9, 最长递增子序列是 1 3 5 7 9
*
* 输入样例:
* 2
* 8
* 5 7 1 8 3 5 7 9
* 9
* 2 1 5 3 6 4 8 9 7
*
* 输出结果:
* 5
* 5
* */
static int T,N=0;
/*
* DP算法设计
* */
public static int dpmax(int[] array,int n) {
if(array.length==0 || n==0) {
return 0;
}
//创建dp数组,其元素用于存放最长递增子序列的长度值
int[] dp=new int[n];
//初始化dp数组元素值为1
Arrays.fill(dp, 1);
//用于存放最大递增子序列的最大长度,初始值为1
int max=1;
for (int i = 0; i <n; i++) {
for (int j = 0; j < i; j++) {
if (array[j] < array[i] )
//状态方程
dp[i] = Math.max(dp[i], dp[j] + 1);
}
//判断dp[i]与max的值谁大,max始终存放最长递增子序列的最大长度
if(dp[i]>max)
max=dp[i];
}
return max;
}
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
System.setIn(new FileInputStream("G:\\LICS.txt"));
Scanner sc = new Scanner(System.in);
T=sc.nextInt(); //读入测试用例组数,即有几组测试用例
int ANSWER=0;
for(int i=1;i<=T;i++) {
N = sc.nextInt();
int[] L = new int[N];
for (int j = 0; j < N; j++) {
L[j] = sc.nextInt();
System.out.print(L[j]+"\t");
ANSWER = dpmax(L,N);
}
System.out.println();
System.out.println("ANSWER = "+ANSWER);
}
}
}
输出结果为:
5 7 1 8 3 5 7 9
ANSWER = 5
2 1 5 3 6 4 8 9 7
ANSWER = 5