栈的入门题,主要考察了栈的基本操作,用递归模拟实现即可
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <cstdlib> 6 using namespace std; 7 const int maxn=30; 8 int n; 9 int top=0,sta[maxn]; 10 int on=0,out[maxn]; 11 int cnt=0; 12 void dfs(int k) { 13 if(on==n) { 14 cnt++; 15 for(int i=1; i<=n; i++) printf("%d",out[i]); 16 printf("\n"); 17 if(cnt==20) exit(0); 18 return ; 19 } 20 if(top>0) { 21 int tp=sta[top--]; 22 out[++on]=tp; 23 dfs(k); 24 sta[++top]=tp; 25 on--; 26 } 27 if(k<=n) { 28 sta[++top]=k; 29 dfs(k+1); 30 top--; 31 } 32 } 33 int main() { 34 scanf("%d",&n); 35 dfs(1); 36 return 0; 37 }