递归改非递归

在递归中,局部变量在每层递归中都占有一部分空间,如果声明过多或递归过深就可能会超过“栈”所能存储的范围,造成栈溢出。

于是,就出现了非递归模拟实现递归的算法。

 

问题:

从 1~n 这 n 个整数中随机选出 m 个,输出所有可能的选择方案。

输入格式

两个整数 n,mn,m ,在同一行用空格隔开。

输出格式

按照从小到大的顺序输出所有方案,每行1个。

首先,同一行内的数升序排列,相邻两个数用一个空格隔开。

其次,对于两个不同的行,对应下标的数一一比较,字典序较小的排在前面(例如1 3 5 7排在1 3 6 8前面)。

数据范围

n>0n>0 ,
0mn0≤m≤n ,
n+(nm)25n+(n−m)≤25

输入样例:
5 3
输出样例:
1 2 3 
1 2 4 
1 2 5 
1 3 4 
1 3 5 
1 4 5 
2 3 4 
2 3 5 
2 4 5 
3 4 5 

 

递归代码:

 

 

#include<iostream>
#include<cstdio>
using namespace std;
int n,m;

void calc(int u,int sum,int state) {
    if (state+n-u<m) return;
    if (state==m) {
        for (int i=0;i<n;++i)
            if (sum>>i&1) cout<<i+1<<" ";
        cout<<endl;
        return;
    }
    calc(u+1,sum|1<<p,s+1);
    calc(u+1,sum,s);
}

int main() {
    cin>>n>>m;
    calc(0,0,0);
    return 0;
}

 

 

 

非递归代码:

 

 

#include<iostream>
#include<cstdio>
#include<stack>    //定义一个栈 
using namespace std;

struct State{
    int pos,u,sum,state;    //pos代表此时模拟递归的位置,用0,1,2表示 
};

int main() {
    int n,m;
    cin>>n>>m;
    stack<State> stk;
    stk.push((State){0,0,0,0});
    while (stk.size()) {
        State t;
        t=stk.top();
        stk.pop();
        if (t.pos==0) {
            if (t.sum+n-t.u<m) continue;
            if (t.sum==m) {
                for (int i=0;i<n;++i) if (t.state>>i&1) cout<<i+1<<" ";
                cout<<endl;
                continue;
            }
            t.pos=1;
            stk.push(t);
            stk.push((State){0,t.u+1,t.sum+1,t.state|1<<t.u});
        }
        else if (t.pos==1) {
            t.pos=2;
            stk.push(t);
            stk.push((State){0,t.u+1,t.sum,t.state});
        }
        else continue;
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/ABBEJ/p/11236558.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值