n个元素进栈,输出所有出栈序列-卡特兰数-递归

#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



*/

  • 2
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值