import java.util.*;
public class Main {
static int N=1010;
static int[] f=new int[N];
static int[] w=new int[N];
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
for(int i=1;i<=n;i++){
w[i]=sc.nextInt();
}
//3 1 2 1 8 5 6
for(int i=1;i<=n;i++){
f[i]=1;
for(int j=1;j<i;j++){
if(w[j]<w[i]){
f[i]=Math.max(f[i],f[j]+1);
}
}
}
int res=0;
for(int i=1;i<=n;i++){
res=Math.max(res,f[i]);
}
System.out.println(res);
}
}
其中数组f记录的是以i为结尾的最长子序列的个数。
若记录路径,使用数组g记录,g记录的是以i为结尾的前一个数字。
import java.util.*;
public class Main {
static int N=1010;
static int[] f=new int[N];
static int[] g=new int[N];
static int[] w=new int[N];
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
for(int i=1;i<=n;i++){
w[i]=sc.nextInt();
}
//3 1 2 1 8 5 6
for(int i=1;i<=n;i++){
f[i]=1;
g[i]=i;
for(int j=1;j<i;j++){
if(w[j]<w[i]){
if(f[i]<f[j]+1){
f[i]=f[j]+1;
g[i]=j;
}
}
}
}
int k=0;
int res=0;
for(int i=1;i<=n;i++)
{
if(res<f[i])
{
res=f[i];
k=i;
}
}
//System.out.println(res);
for(int i=1;i<=res;i++){
System.out.printf("%d ",w[k]);
k=g[k];
}
System.out.println();
System.out.println(res);
}
}
例如:输入3 1 2 1 8 5 6
f[1]=1 g[1]=1
f[2]=1 g[2]=2
f[3]=2 g[3]=2
f[4]=1 g[4]=4
f[5]=3 g[5]=3
f[6]=3 g[6]=3
f[7]=4 g[7]=6