n个元素进栈,输出所有出栈序列-卡特兰数-递归
2016-05-26 17:46
316 查看
#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 */
相关文章推荐
- 出栈顺序与Catalan数
- 【ACM Steps】2.2.6 HDOJ 1023 Train Problem II JAVA解决卡特兰大数问题
- 卡特兰数及括号正确匹配个数问题解释
- 卡特兰数(HDU 1023)
- 1139: 出栈序列统计
- 打印括号匹配的所有排列
- 卡特兰数
- 关于栈的出栈顺序的研究
- 卡特兰数的研究
- hdu 5673 robot【默慈金数or卡特兰数】
- 卡特兰数
- catalan数
- hdu2067 组合数学 卡特兰数
- 工具之卡特兰数(1~100)
- ACM-卡特兰数之Train Problem II——hdu1023
- HDU 1130 How Many Trees?
- HDU 3723 Delta Wave
- HDU 5673 Robot(卡特兰数)
- 卡特兰数的两种计算方法
- HDU1023(JAVA···高精度卡特兰数)