LeedCode_ rise longest sequence
Topic Description
A disorder of a given integer array, the length of the longest found rising sequence.
Input: [10,9,2,5,3,7,101,18]
Output: 4
explained: the longest sequence is increased [2,3,7,101], its length is 4.
Links: https://leetcode-cn.com/problems/longest-increasing-subsequence
Method a: dynamic programming, the time complexity of O (n2)
Assistance state array is the number of records to increase the longest end of the sequence i, the final state of the array need to be traversed to find the maximum value
int lengthOfLIS1(vector<int>& nums)
{
int n = nums.size();
if (n == 0)
return 0;
int maxsize=0;
vector<int> f(n,1); //状态位置f(i)表示以i结尾的最大上升序列的数量
for (int i = 1; i < n; i++)
{
for (int j = 0; j < i; j++)
{
if (nums[i] > nums[j])
{
f[i] = max(f[j] + 1, f[i]);
}
}
maxsize = max(maxsize, f[i]);
}
return maxsize;
}
Method two: dynamic programming + binary search
method using an auxiliary array of recording current rises up sequence, note comments section of the code
int lengthOfLIS2(vector<int>& nums)
{
int n = nums.size();
vector<int>dp; //维护当前的最长序列的内容
for (int i = 0; i < n; i++)
{
int left = 0;
int right = dp.size();
while (left < right)
{
int mid = left + (right - left) / 2;
if (dp[mid] < nums[i])
{
left = mid + 1;
}
else
{
right = mid;
}
}
if (right >= dp.size())
{
dp.push_back(nums[i]); //当前的元素比最大值大,便插入
}
else
{
dp[right] = nums[i]; //当前的元素在范围之内,仅是修改内部的元素(在合适的位置替换元素),不改变数量
}
}
return dp.size();
}