出栈序列统计c语言用回溯,回溯法-出栈序列统计

/*

栈是常用的一种数据结构,有n令元素在栈顶端一侧等待进栈,栈顶端另一侧是出栈序列。

你已经知道栈的操作有两·种:push和pop,前者是将一个元素进栈,后者是将栈顶元素弹出。

现在要使用这两种操作,由一个操作序列可以得到一系列的输出序列。

请你编程求出对于给定的n,计算并输出由操作数序列1,2,…,n,

经过一系列操作可能得到的输出序列总数

*/

#include "stdlib.h"

#include "stdio.h"

int n = 0;/*元素个数*/

int *A = NULL;/*记录序列*/

int *operate = NULL;/*记录栈操作,值为1表示PUSH,值为2表示POP*/

int *Stack = NULL;/*栈数组*/

int Num = 0;/*可能产生的序列的个数*/

/*打印序列*/

void Print ()

{

int i = 0;

printf("%d sequence is as followed:/n", Num);

while (i < 2*n)

{

if (operate[i] == 1)

printf("push ");

if (operate[i] == 2)

printf("pop ");

i++;

}

printf("/n");

}

/*递归统计

stackNum 栈中元素的个数

aNum A中元素个数

nIndex 当前处理的输入序列的下标

*/

void DoStack (int stackNum, int aNum, int nIndex, int operIndex)

{

if (aNum == n)/*n中所有元素均经过入栈和弹栈*/

{

Num++;

Print();

return;

}

if (nIndex > 0)/*入栈*/

{

operate[operIndex] = 1;

Stack[stackNum] = nIndex;

DoStack(stackNum+1, aNum, nIndex-1, operIndex+1);

}

if (stackNum > 0)/*出栈*/

{

operate[operIndex] = 2;

A[aNum] = Stack[stackNum-1];

DoStack(stackNum-1, aNum+1, nIndex, operIndex+1);

}

}

int main ()

{

printf("Please input the n !/n");

scanf("%d", &n);

A = malloc(n*sizeof(int));

operate = malloc(2*n*sizeof(int));/*每个元素都要经过入栈和弹栈*/

Stack = malloc(n*sizeof(int));

DoStack(0, 0, n, 0);

printf("There is %d sequences/n", Num);

free(Stack);

free(operate);

free(A);

system("pause");

return 0;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值