题解 | #最长上升子序列(一)#
最长上升子序列(一)
https://www.nowcoder.com/practice/5164f38b67f846fb8699e9352695cd2f
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 给定数组的最长严格上升子序列的长度。
* @param arr int整型一维数组 给定的数组
* @return int整型
*/
/**
思路:
首先每个数字自身长度为1 所以数组默认填充1
然后遍历每一个dp数组
如果 dp[i] > 某个子序列的末端 dp[i] = 该子序列长度+1
dp[i] = 前面所有子序列长度最长的那个子序列+1
然后用一个flag 记录最大值。
*/
public int LIS (int[] arr) {
// write code here
if( arr.length == 1) return 1;
int res = 0;
int dp[] = new int[arr.length ];
Arrays.fill(dp,1);
for(int i = 1 ; i < arr.length ; i++){
for(int j = 0 ; j < i ; j++){
if(arr[i] > arr[j]){
dp[i] = Math.max(dp[i],dp[j]+1);
}
}
res = Math.max(res,dp[i]);
}
return res;
}
}

查看14道真题和解析