题目描述:
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?
找出最长递增序列,不一定连续。采用动态规划的方法,定义dp[i]表示以nums[i]结尾的最长递增序列长度,对于j<i,如果nums[j]<nums[i],dp[i]=max(dp[j]+1,dp[i]),取最大的dp[i]作为返回值,时间复杂度为O(n)。
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
if(nums.size()==0) return 0;
vector<int> dp(nums.size(),1);
for(int i=1;i<dp.size();i++)
{
for(int j=0;j<i;j++)
{
if(nums[i]>nums[j]) dp[i]=max(dp[j]+1,dp[i]);
}
}
int result=INT_MIN;
for(int i=0;i<dp.size();i++)
{
result=max(result,dp[i]);
}
return result;
}
};
本文介绍了一种求解最长递增子序列(LIS)问题的动态规划算法,该算法的时间复杂度为O(n^2),并通过示例展示了如何实现这一算法。此外,还讨论了如何进一步优化算法至O(n log n)的时间复杂度。

被折叠的 条评论
为什么被折叠?



