最長上升子序列(動態規劃,n²)
阿新 • • 發佈:2018-12-16
package 實驗三; public class 最長上升子序列 { public static void main(String[] args) { E e=new E(); e.way(); e.show1(); e.show2(); e.show3(); e.show4(); } } class E{ int [] a= {5,8,9,2,3}; //資料 int [] b=new int[a.length]; //記錄最長上升子序列的個數 int i=0,j=0; int length; //記錄輸出的下標 int max=0; void way() { for(i=0;i<a.length;i++) { b[i]=1; //一開始全部初始化為1 for(j=0;j<i;j++) { // if(a[j]<a[i] && b[j]+1>=b[i]) b[i]=b[j]+1; } } } void show1() { System.out.print("a[]為:"); for(i=0;i<a.length;i++) { System.out.printf("%-3d",a[i]); } System.out.println(); } void show2() { System.out.print("b[]為:"); for(i=0;i<a.length;i++) { System.out.printf("%-3d",b[i]); } System.out.println(); } void show3() { for(i=0;i<a.length;i++) { if(b[i]>max) max=b[i]; } System.out.println("最長上升序列數為:"+max); } void show4() { int M=max; System.out.print("最長上升序列逆順序為:"); for(i=a.length-1;i>=0;i--) { if(b[i]==M) { System.out.print(a[i]+" "); M--; } } } }
結果
a[]為:5 8 9 2 3 b[]為:1 2 3 1 2 最長上升序列數為:3 最長上升序列逆順序為:9 8 5