Given an unsorted array of integers, find the length of longest increasing subsequence.
Example:
Input:[10,9,2,5,3,7,101,18]
Output: 4 Explanation: The longest increasing subsequence is[2,3,7,101]
, therefore the length is4
.
Note:
- There may be more than one LIS combination, it is only necessary for you to return the length.
- Your algorithm should run in O(n2) complexity.
Follow up: Could you improve it to O(n log n) time complexity?
题目要求找出最长的递增序列,可以不连续,但一定要递增。
在LeetCode中的tag是dp
第一种解法不是dp
class Solution {
public int lengthOfLIS(int[] nums) {
int[] ans=new int[nums.length];
if(nums.length<1)
return 0;
int max=1;
ans[0]=1;
for(int k=1;k<nums.length;k++){
ans[k]=0;
}
for(int i=1;i<nums.length;i++){
for(int j=0;j<i;j++){
if(nums[i]>nums[j])
//找到比他小的最大长度
ans[i]=Math.max(ans[i],ans[j]);
}
ans[i]=ans[i]+1;
max=Math.max(max,ans[i]);
//System.out.println(max);
}
return max;
}
}
找这个数之前比他小的序列的长度。