递归:打印一个序列先入栈再出栈的所有可能

题目:一个序列,比如1,2,3。1入栈之后,有两种情况:一、2入栈;二、1出栈到目标数组。在程序执行的每个时刻都存在这两种肯能,因而会导致打印的结果不一样。要求:打印出所有可能的输出序列

思路:递归遍历所有解空间,注意递归的时候要恢复每步的环境。我程序采用三个数组,源序列src[ ],模拟栈st[ ],目标数组dest[ ](也就是最后要打印的数组)。其中st[0]和dest[0]分别表示当前数组的最后一个元素的下标,初始状态为0,表示数组中没有元素。

程序的c++实现:

stackInOrOut.cpp

#include <iostream>
using namespace std;
void init(int *arr, int start, int end);
void initSrc(int *arr, int start, int end);
void print(int *arr, int start, int end);
void stackInOrOut(int *src, int *st, int *dest, int index, int size, bool flag);
int main()
{
	int size;
	cout << "please input size of src:" << endl;
	cin >> size;
	int *src = new int[size];
	int *st = new int[size + 1], *dest = new int[size + 1];
	initSrc(src, 0, size - 1);
	init(st, 0, size);
	init(dest, 0, size);
	stackInOrOut(src, st, dest, 0, size, true);   //刚开始只能入栈,不能出栈
	delete []src;
	delete []st;
	delete []dest;
}

void init(int *arr, int start, int end)
{
	for (int i = start; i <= end; ++i)
		arr[i] = 0;
}
void initSrc(int *arr, int start, int end)
{
	for (int i = start; i <= end; ++i)
		arr[i] = i + 1;
}
void print(int *arr, int start, int end)
{
	static int count = 1;
	cout << "count = " << count << ",arr[0] = " << arr[0] << '\t';
	for (int i = start; i <= end; ++i)
		cout << arr[i] << ' ';
	cout << endl;
	++count;
}
void stackInOrOut(int *src, int *st, int *dest, int index, int size, bool flag)
{
	if (index == size)
	{
		if (flag == true)	//如果是入栈,打印结果,出栈直接退出
		{
			int j = dest[0];
			for (int i = st[0]; i != 0; --i)
				dest[++j] = st[i];
			print(dest, 1, size);
		}
		return;
	}
	if (true == flag)
	{
		st[++st[0]] = src[index];		//进栈
		stackInOrOut(src, st, dest, index + 1, size, true);
		stackInOrOut(src, st, dest, index + 1, size, false);
		--st[0];						//恢复top指针
	}
	else
	{
		if (st[0] != 0)
		{
			dest[++dest[0]] = st[st[0]--];					//出栈顶元素到目标数组
			stackInOrOut(src, st, dest, index, size, true);
			stackInOrOut(src, st, dest, index, size, false);
			++st[0];										//恢复top指针
			st[st[0]] = dest[dest[0]];						//问题出在这里,原来的程序没有恢复栈中元素的值,只是恢复了top指针
			--dest[0];										//恢复目标数组top指针
		}
	}
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值