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(n2) o(╥﹏╥)o
C++代碼:
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int length = nums.size();
if(length <= 1)
return length;
else
{
int* p = new int[length+1];
int max = 1;
for(int i = 0;i <length;i++)
p[i] = 1;
for(int i = 1;i < length;i++)
for(int j = 0;j < i;j++)
{
if(nums[i] > nums[j]&&p[i] < p[j]+1)
{
p[i] = p[j] + 1;
max = p[i] > max ? p[i] : max;
}
}
return max;
}
}
};