天天看點

給定一個字元串輸出其全部排列的方法

#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;
}
           

用到了一種類似置換的方法~

繼續閱讀