#include <stdio.h>
int counter = 0;
void stack_permutation(int input[], int n, int in_idx, int out_idx, int stack[], int stack_top) {
if (out_idx == n) {
counter++;
for (int i = 0; i < n; i++) {
printf("%d", stack[n + i]);
}
printf("\n");
return;
}
if (stack_top > 0) {
int pop_val = stack[stack_top - 1];
stack_top--;
stack[n + out_idx] = pop_val;
stack_permutation(input, n, in_idx, out_idx + 1, stack, stack_top);
stack_top++;
stack[stack_top - 1] = pop_val;
}
if (in_idx < n) {
stack[stack_top] = input[in_idx];
stack_top++;
stack_permutation(input, n, in_idx + 1, out_idx, stack, stack_top);
}
}
int main() {
int n;
printf("请输入序列长度:");
scanf("%d", &n);
int input[n];
printf("请输入入栈序列(以空格分隔):");
for (int i = 0; i < n; i++) {
scanf("%d", &input[i]);
}
int stack[2 * n];
stack_permutation(input, n, 0, 0, stack, 0);
printf("所有可能的出栈序列的个数:%d\n", counter);
return 0;
}