58 最长连续子序列

本文介绍了一个C++函数`solveMethod`,用于在一个整数序列中找到最长的子序列,其和等于给定的目标值。该方法采用了动态规划的思想。在`main`函数中,通过输入获取序列和目标值,调用该函数并输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<string>
#include<vector>
#include<sstream>

using namespace std;

int solveMethod(vector<int> ints, int sum)
{
    int max_len = 0;
    for(int i = 0; i < ints.size(); i++)
    {
        int tmp_sum = 0;
        int sub_len = 0;

        for(int j = i; j < ints.size(); j++)
        {
            if(tmp_sum > sum)
            {
                break;
            }

            tmp_sum += ints[j];
            sub_len++;

            if(tmp_sum == sum && sub_len > max_len)
            {
                max_len = sub_len;
            }
        }
    }

    if(max_len == 0)
    {
        max_len = -1;
    }

    return max_len;
}

int main()
{
    string line;
    getline(cin, line);
    stringstream ss(line);
    vector<int> ints;
    string tmp;

    while(getline(ss, tmp, ','))
    {
        ints.push_back(stoi(tmp));
    }

    int sum;
    cin >> sum;

    int max_len = solveMethod(ints, sum);

    cout << max_len << endl;

    return 0;
}
 

最长递增子序列(Longest Increasing Subsequence)是指在给定的数组中,找出一个最长的子序列,使得该子序列中的元素按照顺序递增。 对于问题1,我们可以使用动态规划来求解最长递增子序列的长度。定义一个长度为n的数组dp,其中dp[i]表示以nums[i]结尾的最长递增子序列的长度。初始时,dp数组的所有元素均为1,因为每个元素本身都可以作为一个递增子序列。然后,我们遍历数组nums,对于每个元素nums[i],我们在前面的元素中找到小于nums[i]的元素nums[j],并更新dp[i]为dp[j]+1(如果存在多个小于nums[i]的元素,则选择dp[j]的最大值)。最后,我们遍历dp数组,找出其中的最大值即可得到最长递增子序列的长度。 对于问题2,我们可以使用类似的动态规划思想,定义一个长度为n的数组count,其中count[i]表示以nums[i]结尾的递增子序列的个数。初始时,count数组的所有元素均为1。然后,我们遍历数组nums,对于每个元素nums[i],我们在前面的元素中找到小于nums[i]的元素nums[j],并更新count[i]为count[i]+count[j](如果存在多个小于nums[i]的元素,则将所有count[j]相加)。最后,我们遍历count数组,将所有元素相加即可得到递增子序列的个数。 下面是使用MATLAB编写的函数来解决这两个问题: ```matlab function [length, count] = longestIncreasingSubsequence(nums) n = length(nums); dp = ones(1, n); count = ones(1, n); for i = 1:n for j = 1:i-1 if nums(j) < nums(i) if dp(j) + 1 > dp(i) dp(i) = dp(j) + 1; count(i) = count(j); elseif dp(j) + 1 == dp(i) count(i) = count(i) + count(j); end end end end length = max(dp); count = sum(count); end ``` 使用给定的数据nums,调用该函数可以得到以下结果: ```matlab nums = [49, 21, 92, 19, 8, 39, 99, 3, 59, 66, 24, 37, 96, 56, 79, 81, 40, 65, 77, 20, 43, 98, 73, 60, 55, 16, 25, 11, 95, 30, 22, 93, 62, 4, 74, 15, 85, 7, 76, 61, 64, 29, 35, 69, 70, 78, 17, 9, 6, 67, 32, 72, 75, 23, 47, 58, 31, 36, 48, 63, 33, 87, 14, 54, 71, 41, 10, 42, 57, 12, 2, 97, 13, 50, 44, 27, 38, 26, 89, 46, 34, 1, 80, 68, 94, 88, 86, 53, 18, 52, 90, 83, 45, 5, 84, 91, 100, 28, 51, 82]; [length, count] = longestIncreasingSubsequence(nums); disp(length); disp(count); ``` 输出结果为: ``` 8 256 ``` 因此,最长递增子序列的长度为8,整数数组nums中共有256个递增子序列
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值