描述
最长上升子序列的定义:
最长上升子序列问题是在一个无序的给定序列中找到一个尽可能长的由低到高排列的子序列,这种子序列不一定是连续的或者唯一的。
https://en.wikipedia.org/wiki/Longest_increasing_subsequence
样例
给出 [5,4,1,2,3],LIS 是 [1,2,3],返回 3
给出 [4,2,4,5,3,7],LIS 是 [2,4,5,7],返回 4
代码
创建一个数组dp,dp[i]表示,第i个元素的最大上升子序列的长度。
public class Solution {
/*
* @param nums: An integer array
* @return: The length of LIS (longest increasing subsequence)
*/
public int longestIncreasingSubsequence(int[] nums) {
// write your code here
if(nums==null||nums.length==0){
return 0;
}
int[] dp=new int[nums.length];
int max=1;
dp[0]=1;
for(int i=1;i<nums.length;i++){
dp[i]=1;
for(int j=0;j<i;j++){
if(nums[i]>nums[j]){ //大于的话,则判断当前元素的LIS和第j个元素的LIS+1的大小
dp[i]=Math.max(dp[i],dp[j]+1);
max=Math.max(max,dp[i]);
}
}
}
return max;
}
}