题解 | #火车进站#
火车进站
https://www.nowcoder.com/practice/97ba57c35e9f4749826dc3befaeae109
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int n;
int train[10];
int list_n[10];
int list[6000][10];
int stack[10];
int top = -1;
int out = 0;
int indexx = 0;
int kind = 0;
int n;
char result[6000][10];
int cmp(const void* a, const void* b) {
return strcmp((char*)a, (char*)b);
}
void DFS() {
if (out == n) {
for (int i = 0; i < n; i++) {
list[kind][i] = list_n[i];
}
kind++;
return;
}
if (indexx < n) {
stack[++top] = train[indexx++];
DFS();
top--;
indexx--;
}
if (top >= 0) {
list_n[out++] = stack[top--];
DFS();
stack[++top] = list_n[--out];
}
}
int main() {
memset(result, 0, sizeof(result));
while (scanf("%d", &n) != EOF) {
for (int i = 0; i < n; i++) {
scanf("%d", &train[i]);
}
DFS();
for (int i = 0; i < kind; i++) {
for (int j = 0; j < n; j++) {
result[i][j] = list[i][j] + '0';
}
}
qsort(result, kind, sizeof(result[0]), cmp);
for (int i = 0; i < kind; i++) {
for (int j = 0; j < n; j++) {
printf("%c ", result[i][j]);
}
printf("\n");
}
}
return 0;
}

