动态规划-查找最长递增子序列的长度

1、最长连续子序列的长度

Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray).

Example 1:

Input: [1,3,5,4,7]
Output: 3
Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3. 
Even though [1,3,5,7] is also an increasing subsequence, it's not a continuous one where 5 and 7 are separated by 4. 

Example 2:

Input: [2,2,2,2,2]
Output: 1
Explanation: The longest continuous increasing subsequence is [2], its length is 1. 

Note: Length of the array will not exceed 10,000.

这是LeetCode的第674道题,解法如下:

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


2、最长递增子序列的长度

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?


//找到最长递增子序列
int arr[] = {5,3,4,6,8,7,11,38,24};
int num = sizeof(arr)/sizeof(arr[0]);
vector<int> v(arr, arr+num-1);

//思路:动态规划的方法
//以arr[i]结尾的序列最长长度为dp[i]
//dp[0]=1
//dp[1]=1
//dp[2]=dp[1]+1=2
//dp[3]=max(dp[2]+1, dp[1]+1, dp[0]+1)=max(3,2,2)=3
//总结dp[i]的计算方法:和前面的数逐个相比,如果>=a[j], max = max(dp[j+1], max); 如果小于所有a[j] max=1
//          初始化:max=1
//          如果a[i]>=a[j]:max = max(dp[j]+1, max)
class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        vector<int> dp(nums.size(), 1);
        
        int maxLen = 0;
        for(int i=0; i<nums.size(); i++)
        {
            int temp = 1;
            for(int j=0; j<i; j++)
            {
                if(nums[i] > nums[j])
                {
                    temp = max(temp, dp[j]+1);
                }
            }
            
            dp[i] = temp;
            maxLen = max(maxLen, dp[i]);
        }
        
        return maxLen;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值