题目描述:

这里有n列火车将要进站再出站,但是,每列火车只有1节,那就是车头。

这n列火车按1到n的顺序从东方左转进站,这个车站是南北方向的,它虽然无限长,只可惜是一个死胡同,而且站台只有一条股道,火车只能倒着从西方出去,而且每列火车必须进站,先进后出。

也就是说这个火车站其实就相当于一个栈,每次可以让右侧头火车进栈,或者让栈顶火车出站。

车站示意如图:

出站<——    <——进站
|车|
|站|
|__|

现在请你按《字典序》输出前20种可能的出栈方案。

输入格式

输入一个整数n,代表火车数量。

输出格式

按照《字典序》输出前20种答案,每行一种,不要空格。

数据范围

1≤n≤20

输入样例:

3

输出样例:

123
132
213
231
321

我们模拟一下样例:

n = 3
第一种情况:
1. 1 进栈
2. 1 出栈
3. 2 进栈
4. 2 出栈
5. 3 进栈
6. 3 出栈
输出顺序:1 2 3
第二种情况:
1. 1 进栈
2. 1 出栈
3. 2 进栈
4. 3 进栈
5. 3 出栈
6. 2 出栈
输出顺序:1 3 2
······

只要前二十组所以直接搜索,然后模拟栈就行了

AC代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<stdlib.h>
#include<stack>
#include<vector>
#include<math.h>
const int INF = 0x3f3f3f3f;
using namespace std;
typedef long long ll;
typedef double ld;
const int N = 25;
int i,j,k,l;
int n,num=0;
int t=0,top=0;
int ans[N],st[N];
void dfs(int x)
{
if(x==n+1)
{
if(++num>20)
exit(0);//void类型的不能用return结束
for(i=1;i<=t;i++)
printf("%d", ans[i]);
for(i=top;i;i--)
printf("%d", st[i]);
cout<<endl;
return ;
}
if(top)
{
ans[++t]=st[top--];
dfs(x);
st[++top]=ans[t--];
}
st[++top]=x;
dfs(x+1);
--top;
}
int main()
{
cin>>n;
dfs(1);
return 0;
}