[LeetCode 115 C++ Questions] Longest Increasing Subsequence最长的递增子序列

300. Longest Increasing Subsequence最长的递增子序列

Given an integer array nums, return the length of the longest strictly increasing 

subsequence.
给定一个整数数组 nums,返回严格递增的最长长度子序列。

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        int len=nums.size(), res=1; 
        int dp[2505]={0};
        for(int i=0;i<2505;i++){
            dp[i]=1;
        }
        for(int i=1;i<len;i++){
            for(int j=0;j<i;j++){
                if(nums[i]>nums[j]){
                    dp[i]=max(dp[i],dp[j]+1);
                }
            }
            res=max(res,dp[i]);
        }
        return res;
    }
};

2407. Longest Increasing Subsequence II最长的递增子序列 II

You are given an integer array nums and an integer k.

Find the longest subsequence of nums that meets the following requirements:

  • The subsequence is strictly increasing and
  • The difference between adjacent elements in the subsequence is at most k.

Return the length of the longest subsequence that meets the requirements.

subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.

你得到一个整数数组 nums 和一个整数 k。

查找满足以下要求的最长 nums 子序列:

  • 子序列严格增加,并且
  • 子序列中相邻元素之间的差异最多为 k

返回满足要求的最长子序列的长度。

子序列是一个数组,可以通过删除一些元素或不删除一些元素而不改变其余元素的顺序来从另一个数组派生出来。

class Solution {
public:
    void update(vector<int>& tree, int v, int tl, int tr, int pos, int new_val){       
        if(tl == tr){
            tree[v] = max(new_val, tree[v]);
        }else{
            int tm = (tl+tr)/2;
            if(pos<=tm)
                update(tree, v*2, tl, tm, pos, new_val);
            else
                update(tree, v*2+1, tm+1, tr, pos, new_val);
            tree[v] = max(tree[v*2], tree[v*2+1]);
        }
    }

    int get(vector<int>& tree, int v, int tl, int tr, int l, int r){
        if(l>r) return 0;
        if(tl==l && tr==r) return tree[v];

        int tm = (tl+tr)/2;
        return max(
            get(tree, v*2, tl, tm, l, min(tm, r)),
            get(tree, v*2+1, tm+1, tr, max(tm+1, l), r)
        );
    }

    int lengthOfLIS(vector<int>& nums, int k) {
        vector<int> tree(400000, 0);
        for(auto it = nums.begin(); it!=nums.end(); ++it){
            int sub=get(tree, 1, 1, 100000, max(1,(*it)-k), (*it)-1);
            update(tree, 1, 1, 100000, *it, sub+1);
        }        
        return tree[1];
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值