300. Longest Increasing Subsequence

Given an unsorted array of integers, find the length of longest increasing subsequence.

Example:

Input: [10,9,2,5,3,7,101,18]
Output: 4 
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. 

Note:

  • 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:适用于该题的巧妙方法(不能求出具体字符串,只能求出长度) 

复杂度:O(nlogn)(遍历一遍n,lower_bound二分查找logn)

另建一个数组存储最长序列,找到第一个>=当前元素的位置,替换;如果没找到就push_back

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
    //另建一个数组存储最长序列,找到第一个>=当前元素的位置,替换;如果没找到就push_back
        vector<int> res;
        vector<int>::iterator it;
        for(int a:nums){
            it=lower_bound(res.begin(),res.end(),a);//lower_bound:找到大于等于给定值的第一个元素位置,如果没找到返回末尾指针。
            if(it==res.end()) res.push_back(a);
            else *it=a;
        }
        return res.size();
    }
 };

方法2:动态规划(n^2)

创建一个数组存储以第i个元素为结尾的最大递增子串。

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        int n=nums.size();
        if(n==0) return 0;
        vector<int> lenArr(n,1);
        int maxL=1;
        for(int i=1;i<n;i++){
            for(int j=0;j<i;j++){
                if(nums[i]>nums[j]&&lenArr[j]+1>lenArr[i]){
                    lenArr[i]=lenArr[j]+1;
                    if(lenArr[i]>maxL) maxL=lenArr[i];
                }
            }
        }
        return maxL;
    }
    
 };

方法3:深度优先搜索(超时)

class Solution {
public:
   int lengthOfLIS(vector<int>& nums) {
        if(nums.size()==0) return 0;
        int len=1;
        for(int i=0;i<nums.size()-1;i++){
            len=max(dfs(i+1,nums[i],1,nums),len);
        }
        return len;
    }
    int dfs(int i,int maxN,int len, vector<int> &nums){
        if(i>=nums.size()) return len;
        if(nums[i]>maxN){
            return max(dfs(i+1,maxN,len,nums),dfs(i+1,nums[i],len+1,nums));
        } else return dfs(i+1,maxN,len,nums);    
    }
};

 

点赞