dp求最长递增子序列并输出
1 import java.util.ArrayList; 2 import java.util.Arrays; 3 import java.util.List; 4 5 /** 6 * Created on 2016/4/26. 7 */ 8 public class Testdp { 9 10 public static void main(String[] args) { 11 new Testdp().getLIS(); 12 } 13 14 public void getLIS() { 15 List<Integer> nums = null; 16 Integer[] numArray = {1, 4, 8, 1, 2, 3, 5}; 17 nums = Arrays.asList(numArray); //输入的数据 18 int len = nums.size(); 19 20 String[] result = new String[len]; // 用来存储输出字符串 21 int dp[] = new int[len]; 22 23 for (int i = 0; i < len; ++i) { 24 dp[i] = 1; 25 result[i] = "" + nums.get(i); 26 27 for(int j=0; j<i; ++j) { 28 if (nums.get(j) < nums.get(i) && dp[j] + 1 > dp[i]) { 29 result[i] = result[j] + " " + nums.get(i); 30 dp[i] = dp[j] + 1; 31 } 32 } 33 } 34 35 int maxLen = 0; 36 int maxIndex = 0; 37 for(int i=0; i<len; ++i) { 38 if (maxLen < dp[i]) { 39 maxLen = dp[i]; 40 maxIndex = i; 41 } 42 } 43 System.out.println(result[maxIndex]); 44 System.out.println(maxLen); 45 46 } 47 48 }