Generate all Letter Combinations [closed]

北慕城南 提交于 2019-12-12 02:54:52

问题


Can someone help me get a C algorithm to generate all letter combinations of length n?

I need the output to be like:

aaaaaaa
aaaaaab
aaaaaac
.
.
.
zzzzzzx
zzzzzzy
zzzzzzz



for(i = 0; i<length; i++){
    pass[i] = 'a';
}

while(1){
    for(j=0;j<26;j++){
        printf("%s\n",pass);
        pass[i] = (char)(pass[i]+1);
    }
    if(pass[i-1]==z)...
}
return 0;

回答1:


Here's a version using recursion:

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

void iterate(char *str, int idx, int len) {
    char c;

    if (idx < (len - 1)) {
        for (c = 'a'; c <= 'z'; ++c) {
            str[idx] = c;

            iterate(str, idx + 1, len);
        }
    } else {
        for (c = 'a'; c <= 'z'; ++c) {
            str[idx] = c;

            printf("%s\n", str);
        }
    }
}

#define LEN 3

int main(int argc, char **argv) {
    char str[LEN + 1];

    memset(str, 0, LEN + 1);

    iterate(str, 0, LEN);
}



回答2:


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

int isFinish(char *str){
    return '\0'== str[strspn(str, "z")];
}

void inc_str(char *str){
    int index, carry;
    for(index = strlen(str)-1;index>=0;--index){
        if(str[index] == 'z'){
            carry = 1;
            str[index] = 'a';
        } else {
            carry = 0;
            str[index] += 1;
        }
        if(carry == 0)break;
    }
}

int main(){
    int n;
    char *str;

    n=7;//length
    str=(char*)malloc(sizeof(char)*(n+1));
    //initialize
    memset(str, 'a', n);//"aa..aa"
    str[n]='\0';

    while(1){
        printf("%s\n", str);
        if(isFinish(str))
            break;
        inc_str(str);
    }
    free(str);
    return 0;
}


来源:https://stackoverflow.com/questions/10159649/generate-all-letter-combinations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!