递归全排列

来源:互联网 发布:安卓音乐播放器 知乎 编辑:程序博客网 时间:2024/05/09 00:56
#include <stdio.h>
#include <stdlib.h>
#define SWAP(x, y, t) ((t)=(x), (x)=(y), (y)=(t))
int count = 0;
void perm(char* list, int m, int n)
{
    char temp;
    int i;
    if (m==n)
    {
        printf("%s %d\n", list, ++count);
    }
    else
    {
        for (i = m; i <= n;i++)
        {
            SWAP(list[m], list[i], temp);//从第二个数开始依次与第一个数互换
            perm(list, m + 1, n);//求第二个数到最后一个数字的全排列
            SWAP(list[m], list[i], temp);//互换的还原
        }
    }
}
void main()
{
    char list[] = "abc";
    perm(list, 0, 2);
    printf("总共有%d种排列方式.\n", count);

    system("pause");
}
0 0