天天看点

给定一个字符串输出其全部排列的方法

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int count = 0;

typedef struct
{
    int exist;//这个字符是否存在于字符串中
    int *used;//这个字符在全排列处理过程中是否在i位置固定过
}alphabet;//字母表结构体,用哈希表的形式做记录,可以让查询时间缩短至O(1)。

void wholeArray(char *a, char nowlength, alphabet *records)
{
    int i;
    char guard;
    alphabet temp[26];
    int j, t;
    if(nowlength == 1)
    {
        count ++;
        printf("%s\n", a);
    }//递归到底层,输出结果
    else
    {
        for(i = 0; i < nowlength; i ++)
        {
            if(records[a[i] - 'a'].used[nowlength - 1] == 1)//如果这个字符曾经在该位置固定过,则跳过本轮处理
            {
                continue;
            }
            else
            {
                records[a[i] - 'a'].used[nowlength - 1] = 1;
                guard = a[nowlength - 1];
                a[nowlength - 1] = a[i];
                a[i] = guard;
                for(j = 0; j < 26; j ++)
                {
                    temp[j].exist = records[j].exist;
                    if(temp[j].exist == 1)
                    {
                        temp[j].used = (int *)malloc(strlen(a) * sizeof(int));
                        for(t = 0; t < strlen(a); t ++)
                        {
                            temp[j].used[t] = records[j].used[t];
                        }
                    }
                }//用temp表复制records表,并传入到递归的下一层中,以免破换records的值,因为records只有在最顶级的循环处理中才能更改,它表示某一个字符所有的全排列结果都已得到
                wholeArray(a, nowlength - 1, temp);
                a[i] = a[nowlength - 1];
                a[nowlength - 1] = guard;//返回上层递归时要将局部字符串回归原样
            }
        }
    }
}

int main()
{
    char a[10];
    alphabet records[26];
    int i,j;
    while(scanf("%s", a) != EOF)
    {
        for(i = 0; i < 26; i ++)
        {
            records[i].exist = 0;
        }
        for(i = 0; i < strlen(a); i ++)
        {
            if(records[a[i] - 'a'].exist == 0)
            {
                records[a[i] - 'a'].exist = 1;
                records[a[i] - 'a'].used = (int *)malloc(strlen(a) * sizeof(int));
                for(j = 0; j < strlen(a); j ++)
                {
                    records[a[i] - 'a'].used[j] = 0;
                }
            }
        }
        count = 0;
        wholeArray(a, strlen(a), records);
        printf("count = %d\n", count);
    }
    return 0;
}
           

用到了一种类似置换的方法~

继续阅读