package com.wentora.exercise; /** * 两种方法求数组中最大递增序列 * 思想:以第k位为最后元素的最大递增序列长度等于前面以第k-1位元素为最后元素的最大递增序列长度加1 * 前提是第k位元素必须大于该元素,否则以它为最后元素的最大递增序列长度等于1 * 递归式求解 * 动态规划 * @author wentora */ import java.util.Scanner; public class LIS { private int[] a; private int[] b; LIS(int[] a) { this.a = a; b = new int[a.length]; } //递归式求解 public int getLIS(int len) { if(len == 1) return 1; int temp = -1; for(int i = 0; i < len - 1; i++) { if(a[len - 1] > a[i] && temp < getLIS(i + 1)) { temp = getLIS(i + 1); } } return temp + 1; } //该方法求得以每一位为最后元素的最大序列的长度 public void getLIS1(int len) { int temp = 0; for(int i = 0; i < len; i++) { if(a[len - 1] > a[i] && temp < b[i]) { temp = b[i]; } } b[len - 1] = temp + 1; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.print("please input size : "); Scanner in = new Scanner(System.in); int size; size = in.nextInt(); int a[] = new int[size]; System.out.print("pleae input array : "); for(int i = 0; i < size; i++) a[i] = in.nextInt(); LIS lis = new LIS(a); int[] c = new int[size]; for(int i = 1; i <= size; i++) c[i - 1] = lis.getLIS(i); int amax = -1; for(int i = 0; i < size; i++) if(amax < c[i]) amax = c[i]; for(int i = 1; i <= size; i++) lis.getLIS1(i); int max = -1; for(int i = 0; i < lis.b.length; i++) { if(max < lis.b[i]) max = lis.b[i]; } System.out.println("the lis by dynamic programming is : " + max); System.out.print("the lis by recursion is : " + amax); } }