leetcode rise longest sequence of dynamic programming

A disorder of a given integer array, the length of the longest found rising sequence.

Example:

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.
Description:

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/longest-increasing-subsequence

Algorithm 1: The f [i] represents the end of a subscript i rise longest sequence, every time i have a decision-making before i need to find the longest and the ratio of nums [i] small f [j], time complexity is n

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        
        //base case
        if(nums.empty())return 0;
        vector<int> f(nums.size());
        f[0]=1;
        int ans=f[0];
        for(int i=1;i<nums.size();++i){
            for(int j=0;j<i;++j){
                if(nums[i]>nums[j])
                    f[i]=max(f[j]+1,f[i]);
                else f[i]=max(f[i],1);
            }
            ans=max(ans,f[i]);
        }
        return ans;
    }
};

Two algorithms: nlogn here to optimize the search for the longest length smaller than the current value, with half to come, because we can find In terms of length of index, so if nums stored value, is monotone, the reductio ad absurdum, if , then less than the length of the front behind the front than the back of a certain length, there is a conflict, an error is assumed, monotonicity find we can use two points to find the current value is smaller than the longest length, l = 0, r = len;

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        vector<int> sum(nums.size()+10);
        int len=0;
        sum[0]=-2e9;
        for(int i=0;i<nums.size();++i){
            int l=0,r=len;
            while(l<r){
                int mid=l+r+1>>1;
                if(sum[mid]<nums[i])l=mid;
                else r=mid-1;
            }
            len=max(len,r+1);
            sum[r+1]=nums[i];
        }
        return len;
    }
};

Guess you like

Origin www.cnblogs.com/clear-love/p/11371457.html