n個元素進棧,輸出所有出棧序列-卡特蘭數-遞迴
阿新 • • 發佈:2019-01-07
#include <iostream> #include <stack> #include <queue> #include <algorithm> #include <string.h> #include <cstdio> #include <stdlib.h> #include <cctype> #include <stack> #include <queue> using namespace std; void printAllOutStackSeq( queue<int> inQueue, int n, stack<int> st, queue<int> out ) { if( n <= 0 || ( inQueue.empty() && st.empty() && out.empty() ) ) { return; } if( out.size() == n ) { while( !out.empty() ) { cout << out.front() << ' '; out.pop(); } cout << endl; return; } stack<int> stCopy = st; // 備份一下,否則儲轉 queue<int> outCopy = out; if( !st.empty() ) // 出棧,將元素出棧,push到結果佇列中 { out.push( st.top() ); st.pop(); printAllOutStackSeq( inQueue, n, st, out ); } if( !inQueue.empty() ) // 入棧,將輸入隊列出隊,進行入棧 { stCopy.push( inQueue.front() ); inQueue.pop(); printAllOutStackSeq( inQueue, n, stCopy, outCopy ); } return; } int main() { int ret = 0; int a[] = { 1, 2, 3, 4 }; queue<int> inQueue; for( int i = 0; i < 4; i++ ) { inQueue.push( a[i] ); } int n; stack<int> st; queue<int> out; printAllOutStackSeq( inQueue, 4, st, out ); return ret; } /* n個元素入棧,出棧序列個數: C(2n,n)/(n+1) ./a.out 1 2 3 4 1 2 4 3 1 3 2 4 1 3 4 2 1 4 3 2 2 1 3 4 2 1 4 3 2 3 1 4 2 3 4 1 2 4 3 1 3 2 1 4 3 2 4 1 3 4 2 1 4 3 2 1 ./a.out|wc -l 14 */