在递归中,局部变量在每层递归中都占有一部分空间,如果声明过多或递归过深就可能会超过“栈”所能存储的范围,造成栈溢出。
于是,就出现了非递归模拟实现递归的算法。
问题:
从 1~n 这 n 个整数中随机选出 m 个,输出所有可能的选择方案。
输入格式
两个整数 n,mn,m ,在同一行用空格隔开。
输出格式
按照从小到大的顺序输出所有方案,每行1个。
首先,同一行内的数升序排列,相邻两个数用一个空格隔开。
其次,对于两个不同的行,对应下标的数一一比较,字典序较小的排在前面(例如1 3 5 7排在1 3 6 8前面)。
数据范围
n>0n>0 ,
0≤m≤n0≤m≤n ,
n+(n−m)≤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; }