编程之美-数组中最长递增子序列(包括输出)

本文探讨了如何在数组中找到最长递增子序列,并通过回溯法输出所有可能的最长递增子序列。
#include <iostream>
#define N 8
using namespace std;
int main(){    
    int a[N]={1,-1,2,-3,4,-5,6,-7};
    int lis[N];
    int result[N];//结果
    for(int i=0;i<N;i++)
            result[i]=0;
    for(int i=0;i<N;i++)
    {
        lis[i]=1;
        for (int j=0;j<i; j++)
        {
            if( a[i]> a[j] && lis[i] < lis[j]+1){
                lis[i]=lis[j]+1;
            }
        }        
    }
    int m=0;
    for(int i=0;i<N;i++){
        if(m<lis[i])
            m=lis[i];
    }
    cout<<"最长递增子序列为:"<<m<<endl;
    //用回溯法输出最长递增子序列
    int b=m;
    int sum=0;
    for(int t=N;t>=0;t--){
        if (b > m)
            break;
        if(lis[t] == b){
            result[t]=1;
            b=b-1;
            if(b  ==  0){
                char p[30];
                sprintf(p,"第%d个最长递增子序列",++sum);
                cout<<p<<endl;
                //输出
                for(int g=0;g<N;g++){
                    if(result[g] == 1)
                         cout<<a[g]<<" ";
                }
                cout<<endl;
                //复原
                b=b+1;
                result[t]=0;
            }

        }
        if( t == 0){
            b=b+1;
            int r;
            //回溯
            for(r=0;result[r]!=1&&r<N;r++);
            if(r<N){
                t=r;
                result[t]=0;
            }
        }
    }    
    system("pause");
    return 0;
}

 

最长递增子序列为:4
第1个最长递增子序列
-1 2 4 6
第2个最长递增子序列
1 2 4 6

转载于:https://www.cnblogs.com/sklww/p/3740066.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值