ITPub博客

首页 > Linux操作系统 > Linux操作系统 > 一个简单的编程

一个简单的编程

原创 Linux操作系统 作者:reaphix 时间:2009-11-09 15:44:27 0 删除 编辑

题是如下,

定义一个数组,编程打印它的全排列。比如定义:

#define N 3
int a[N] = { 1, 2, 3 };
则运行结果是:

$ ./a.out
1 2 3
1 3 2
2 1 3
2 3 1
3 2 1
3 1 2
1 2 3

我的代码是下面的.
不知道有没有更简单的方法...


#include
#include
#define N 5

int a[N];

void print_all(int count)
/*
 * 使用的方法是:
 * 把序列分成第一个数和期于的数
 * 然后对期于的数进行所有可能的排序
 * 当期于的数的个数为 2 时, 就把两种情况打印出来
 * 最后,把顺序恢复过来
 * 史进入函数时的顺序和结束时是保持一致的。
 * 解释的可能不清楚。。
 */
{
  int i, j, temp;
  if(N - count == 2)  // When remnant two number, then print
  {
    for(i = count; i < N; i++)
    {
      printf("{");
      for(j = 0; j < N; j++)
      {
        printf("%d ",a[j]);
      }
        temp = a[count];
        a[count] = a[count + 1];
        a[count + 1] = temp;
      printf("\b}\n");
    }
  }
  else
  {
    for(i = count; i < N; i++)
    {
      temp = a[count];      // swap the "count"th number and "i"th number
      a[count] = a[i];
      a[i] = temp;
      print_all(count + 1);
      temp = a[count];      // return two number's old values
      a[count] = a[i];
      a[i] = temp;
    }
  }
}

int main(void)
{
  int i;
  for(i = 0; i < N; i++)
    a[i] = i;
  print_all(0);
  for(i = 0; i < N; i++)
    printf("%d", a[i]);
  printf("\n");
}

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/8310173/viewspace-618422/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: 终于考到了...
下一篇: 没有了~
请登录后发表评论 登录
全部评论

注册时间:2009-08-24

  • 博文量
    12
  • 访问量
    14605