最长递增子序列

 问题:

  求解一个数组的最长递增子序列。

思路:

  如果要求一个问题的最优解(通常是最大值或者最小值),而且该问题能够分解成若干个子问题,并且小问题之间也存在重叠的子问题,则考虑采用动态规划。

示例:

1 arr[] = {3,1,4,1,5,9,2,6,5}
2 最长递增子序列长度为4。
3 即为:1,4,5,9

code:

 1 public class Dp {
 2 
 3     public static int LIS(int[] A){
 4         int result = 1;
 5         int[] B = new int[A.length];         //存放每一个节点的LIS
 6         for (int i = 0; i < B.length; i++) { //初始化
 7             B[i] = 1;
 8         }
 9         for (int i = 1; i < A.length; i++) {
10             for (int j =0; j < i; j++){
11                 if(A[j] < A[i]){
12                     B[i] = Math.max(B[i], B[j]+1);
13                 }
14             }
15             result = Math.max(result, B[i]);
16         }
17         return result;
18     }
19 
20     public static void main(String[] args) {
21         System.out.println(LIS(new int[]{10, 9, 2, 5, 3, 7, 101, 18}));
22     }
23 }

 

posted @ 2018-09-04 18:57  110255  阅读(101)  评论(0编辑  收藏  举报