300. Longest Increasing Subsequence
Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given [10, 9, 2, 5, 3, 7, 101, 18]
,
The longest increasing subsequence is [2, 3, 7, 101]
, therefore the length is 4
. Note that 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?
解题思路:
题目是让求一个最长递增子序列
方法1:使用动态规划,转移方程为d[i]=max(d[i],d[j]+1),条件为(d[i]>d[j],0<=j<i); 时间复杂度为o(n) 空间复杂度为o(n);
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int len=nums.size();
if(len==0)return 0;
int ans=1;
vector<int> dp(len,1);
for(int i=len-2;i>=0;i--){
for(int j=len-1;j>i;j--){
if(nums[i]<nums[j]){
dp[i]=max(dp[i],dp[j]+1);
ans=max(dp[i],ans);
}
}
}
return ans;
}
};
方法2:使用一个数组来存储递增序列,从前往后遍历,每次把当前元素储存在数组的第一个大于它的位置,如果没找到则把该数加到数组末尾。最后返回数组长度即可。
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int len = nums.size();
if (len == 0)return 0;
vector<int> ans;
for (int i = 0; i < len; i++) {
auto it = lower_bound(ans.begin(),ans.end(),nums[i]);
if (it == ans.end())ans.push_back(nums[i]);
else *it = nums[i];
}
return ans.size();
}
};