最长递减子序列

该博客介绍了一个算法问题,即如何找到一个整数数组的最长递减子序列。通过提供C++代码实现,博客展示了如何遍历数组并维护状态来找到最长递减子序列,最终给出输入数组`9, 4, 3, 2, 5, 4, 3, 2`的最长递减子序列`9, 5, 4, 3, 2`。" 118243439,10873281,Spring Security深度解析与实战,"['Java', '安全', 'Spring Framework', '面试准备', 'Spring Security']

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

/**
 * 求一个数组的最长递减子序列
 *输入:9,4,3,2,5,4,3,2
 *输出:9,5,4,3,2
 **/
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

struct state
{
	int index_pre; //存储当前值的前一个值的位置
	int length; //存储到当前位置的长度
	state()
		:index_pre(-1)
		,length(0)
	{
	}
};

int* get_lds(int* arr,int size,int& length)
{
	if(size==0 || arr==nullptr)
		return nullptr;
	state* st=new state[size];
	int last_pos; //存储最长的结束位置
	int last_long=-1; //存储至今的最长串
	for(int i=0;i<size;++i)
	{
		int cur_length=1; //存储当前最长
		int cur_pre=-1; //存储上一个位置
		for(int j=0;j<i;++j) 
		{
			if(arr[i]<arr[j] && cur_length<st[j].length+1)
			{
				cur_pre=j;
				cur_length=st[j].length+1;
			}
		}
		st[i].length=cur_length;
		st[i].index_pre=cur_pre;
		if(cur_length>last_long) //存储至今最长
		{
			last_long=cur_length;
			last_pos=i;
		}
	}
	//cout<<st[last_pos].length<<endl;
	length=st[last_pos].length;
	int *result=new int[st[last_pos].lengt
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值