1 public class Exp5_1 {
2
3 //给定一个整数数组,设计一个动态规划算法求出该数组中的最长递增子序列。
4 public static void main(String[] args) {
5 // TODO Auto-generated method stub
6 int[] arr=new int[]{5,2,8,6,3,6,9,7};
7 computeMaxIncreaList(arr);
8 //最长递增子序列的长度为: 4
9 //序列为: 2 3 6 9
10
11 int[] arr2=new int[]{4,5,3,2,1,6,7,5,8,9,6,5};
12 computeMaxIncreaList(arr2);
13 //最长递增子序列的长度为: 6
14 //序列为: 4 5 6 7 8 9
15 }
16
17 public static void computeMaxIncreaList(int[] arr){
18 if(arr==null||arr.length==0)
19 return;
20
21 int[] prev=new int[arr.length]; //记录最长子序列中该元素的前一个元素的位置
22 int[] len=new int[arr.length]; //记录以该元素为终点的最长子序列的长度
23 prev[0]=-1; //若没有前驱元素记为-1
24 len[0]=1;
25 for(int i=1;i<arr.length;i++){
26 len[i]=1; //最小长度为1
27 boolean hasSmall=false; //记录该元素前面是否有更小的元素
28 for(int j=i-1;j>=0;j--){
29 if(arr[j]<arr[i]){ //元素为递增
30 hasSmall=true;
31 if(len[j]+1>len[i]){
32 len[i]=len[j]+1;
33 prev[i]=j;
34 }
35 }
36 }//内for
37 if(!hasSmall)
38 prev[i]=-1;
39 }//外for
40
41 int maxLen=len[0]; //记录最长递增子序列长度
42 int maxLenIndex=0; //记录最长递增子序列的终点位置
43 for(int i=1;i<arr.length;i++){
44 if(len[i]>maxLen){
45 maxLen=len[i];
46 maxLenIndex=i;
47 }
48 }
49
50 //打印序列长度及序列元素
51 System.out.println("最长递增子序列的长度为: "+len[maxLenIndex]);
52
53 String path=String.valueOf(arr[maxLenIndex]);
54 int preIndex=prev[maxLenIndex];
55 while(prev[preIndex]!=-1){
56 path=String.valueOf(arr[preIndex])+" "+path;
57 preIndex=prev[preIndex];
58 }
59 path=String.valueOf(arr[preIndex])+" "+path;
60 System.out.println("序列为: "+path);
61 }
62 }