基礎資料結構~
阿新 • • 發佈:2020-12-26
飛速刷題進行時~
markdown果然好用w
0x11棧
我到底是什麼時候寫的前兩道題???
·火車進站
那麼只能用遞迴法:
對於每一個狀態,顯然的我們只有兩種選擇:
1、把下一個數進棧
2、把當前數出棧(棧非空)
時間複雜度O(2^N)
程式碼:
#include<cmath> #include<cstdio> #include<cstdlib> #include<iostream> #include<algorithm> using namespace std; const int N=30; int zh[N],ans[N],top=0,cz=0,num=0,n;//棧陣列、答案陣列、棧頂 void dfs(int x) { if(x==n+1) { if(num>=20) exit(0); num++; for(int i=1;i<=cz;i++) printf("%d",ans[i]); for(int i=top;i>=1;i--) printf("%d",zh[i]);//把沒出棧的一次性出了 printf("\n"); return; } if(top)//棧非空 { ans[++cz]=zh[top--]; dfs(x); zh[++top]=ans[cz--]; } top++; zh[top]=x; dfs(x+1); top--; } int main() { scanf("%d",&n); dfs(1); return 0; }