长度为 N 的字母表中所有字母的排列

Permutation of all Letters of the Alphabet with length N

我最近开始了一个用 C 语言处理暴力密码破解和加密的个人项目。我一直在尝试开发一个输出长度为 N 的字母表的所有可能组合的函数。例如,如果 N = 4,则必须输出 aaaa - zzzz 的所有可能性。从逻辑上讲,我不明白我应该如何递归地处理这个问题。

char* alphabet[] = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};

void passwords(int size){
    char* password[size];
    char* result;
    //Determining static letter
    for(int i = 0; i < size; i++){
        for(int x = 0; x < size; x++){
            password[x] = "a";
        }
        int index = i+1; //password index to modify 
        while(index < size){
            for(int j = 0; j < 26; j++){
                password[i] = alphabet[j];
                printf("%s\n",password);
                
            }
            index++;
        }
    }
}
int main(int argc, char* argv[]){
    passwords(3);
    return 0;
}

目前该程序仅修改字母表中的一个字符并产生以下输出:

aaa
baa
caa
daa
...//e-z aa
aaa
aba
aca
ada
...//a e-z a
aaa
aab
aac
aad
...//aa e_z

任何建议都将非常感谢!

如果递归的使用不是强制要求,请尝试:

#include <stdio.h>
#include <stdlib.h>
#define N 26                                    // number of alphabets

void passwords(int size) {
    int i;
    char *password;

    if (NULL == (password = malloc(size + 1))) {
        perror("malloc");
        exit(1);
    }

    for (i = 0; i < size; i++) {
        password[i] = 'a';                      // initialize the array
    }
    password[i] = '[=10=]';                         // terminate the string

    while (1) {
        printf("%s\n", password);
        password[size - 1]++;                   // increment rightmost character
        for (i = size - 1; i >= 0; i--) {
            if (password[i] >= 'a' + N) {       // carry over
                if (i == 0) {                   // end of permutation
                    free(password);
                    return;
                } else {
                    password[i] = 'a';
                    password[i - 1]++;
                }
            }
        }
    }
}

int main()
{
    passwords(3);
    return 0;
}