【问题标题】:Generate all Letter Combinations [closed]生成所有字母组合[关闭]
【发布时间】:2012-04-26 22:16:58
【问题描述】:

有人可以帮我获得一个 C 算法来生成长度为 n 的所有字母组合吗?

我需要输出是这样的:

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;

【问题讨论】:

    标签: c combinations permutation


    【解决方案1】:

    这是一个使用递归的版本:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-18
        • 1970-01-01
        • 1970-01-01
        • 2011-11-11
        相关资源
        最近更新 更多