|
模拟递归
- #include<iostream>
- #include<algorithm>
- #include<vector>
- #include<iomanip>
- const int maxn = 100010;
- using namespace std;
- int stackn[maxn];
- int top, address;
- int n,m;
- vector<int> choose;
- void call(int x, int retadd){
- int last = top;
- stackn[++top] = x;///现在的
- stackn[++top] = retadd;///返回地址
- stackn[++top] = last;///上一个的栈顶
- }
- int ret(){
- int retadd = stackn[top - 1];///返回地址
- top = stackn[top];///还原到上一个栈顶
- return retadd;
- }
- int main(){
- cin>>n>>m;
- call(1, 0);///开始
- while(top){
- int x = stackn[top-2];///现选的数
- if(!address){///限制边界条件
- if(choose.size()>m ||choose.size()+(n-x+1)<m){
- address = ret();
- continue;
- }
- if(x == n+1){
- for(int i=0; i<choose.size(); i++)
- cout<<setw(3)<<choose[i];
- cout<<endl;
- address = ret();
- continue;
- }
- call(x+1, 1);///选下一个
- address = 0;
- continue;
- }
- if(address == 1){
- choose.push_back(x);
- call(x+1, 2);
- address = 0;
- continue;
- }
- if(address == 2){
- choose.pop_back();///回溯
- address = ret();
- }
- }
- return 0;
- }
复制代码
没必要这么复杂,你理解透彻之后再重做一下。 |
|