题解 | #火车进站#

火车进站

https://www.nowcoder.com/practice/97ba57c35e9f4749826dc3befaeae109

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char list[6000][10];
int stack[10];
int train[10];
int kind = 0;
int n;
int cmp_char(const void *_a, const void *_b)
{
    char *a = (char *)_a;
    char *b = (char *)_b;
    return strcmp(a, b);
}
void DFS(int pos,int top,int index)
{
    if(pos == n)
    {
        kind ++ ;
        for(int i=0;i<n;i++)
        {
            list[kind][i] = list[0][i];
        }
        return;
    }
    if(index < n)
    {
        stack[++top] = train[index++];
        DFS(pos,top,index);
        top--;
        index--;
    }

    if(top>=0)
    {
        list[0][pos++] = stack[top--] + '0';
        DFS(pos,top,index);
        stack[++top] = list[0][--pos] - '0';
    }
}
int main()
{
  while (scanf("%d", &n) != EOF)
  {
    for (int i = 0; i < n; i++)
    {
      scanf("%d", &train[i]);
    }
    int top = -1;
    int index = 0;
    DFS(0, top, index);
    qsort(list + 1, kind, sizeof(list[1]), cmp_char);
 
    for (int i = 1; i <= kind; i++)
    {
      for (int j = 0; j < n; j++)
      {
        printf("%c ", list[i][j]);
      }
      printf("\n");
    }
  }
 
  return 0;
}

全部评论

相关推荐

05-20 21:57
已编辑
门头沟学院 Java
喜欢吃卤蛋的悲伤蛙在提需求:建信融通没消息吧,我2说有实习挂简历不理了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务