LeetCode 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?
分析
这道题先用时间复杂度为O(n^2)的做法来做,dp[i] 表示以nums[i]为结尾的最大非递减子列长度,状态转移方程 if(nums[i]>nums[j]) dp[i]=max(dp[i] ,dp[j]+1), 用maxn记录最大值即可。
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
if(nums.size()==0) return 0;
vector<int> dp(nums.size(),1);
dp[0]=1; int maxn=1;
for(int i=1;i<nums.size();i++){
for(int j=i-1;j>=0;j--)
if(nums[i]>nums[j])
dp[i]=max(dp[i],dp[j]+1);
maxn=max(maxn,dp[i]);
}
return maxn;
}
};
继续分析
可以用stl里的lower_bound写出时间复杂度为O(n*lg(n) )的算法,
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
vector<int> res;
for(int i=0; i<nums.size(); i++) {
auto it = std::lower_bound(res.begin(), res.end(), nums[i]);
if(it==res.end()) res.push_back(nums[i]);
else *it = nums[i];
}
return res.size();
}
};