Solution 1: dp
class Solution {
public int lengthOfLIS(int[] nums) {
if(nums.length==0)return 0;
int[] dp=new int[nums.length+1];
dp[0]=1;
int maxans=1;
for(int i=1;i<nums.length;i++){
int maxval=0;
for(int j=0;j<i;j++){
if(nums[i]>nums[j]){
maxval=Math.max(maxval,dp[j]);
}
}
dp[i]=maxval+1;
maxans=Math.max(maxans,dp[i]);
}
return maxans;
}
}
Solution2 :dp+二分搜索
这里dp的长度才是答案,和dp里面存的是哪些数没有关系
input: [0, 8, 4, 12, 2]
dp: [0]
dp: [0, 8]
dp: [0, 4]
dp: [0, 4, 12]
dp: [0 , 2, 12] which is not the longest increasing subsequence, but length of dpdp array results in length of Longest Increasing Subsequence.
public int lengthOfLIS(int[] nums) {
if(nums == null || nums.length == 0) {
return 0;
}
int[] dp = new int[nums.length];
dp[0] = nums[0];
int len = 0;
for(int i = 1; i < nums.length; i++) {
if(nums[i] > dp[len]) {
dp[++len] = nums[i];
}
else {
int index = search(dp, len, nums[i]);
dp[index] = nums[i];
}
}
return len + 1;
}
private int search(int[] dp, int len, int val) {
int start = 0;
while(start <= len) {
int mid = start + (len - start) / 2;
if(dp[mid] == val) {
return mid;
}
else if(dp[mid] < val) {
start = mid + 1;
}
else {
len = mid - 1;
}
}
return start;
}