生成所有字母组合 [英] Generate all Letter Combinations
本文介绍了生成所有字母组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以帮我得到一个C算法来生成长度为n的所有字母组合吗?
Can someone help me get a C algorithm to generate all letter combinations of length 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;
推荐答案
以下是使用递归的版本:
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);
}
这篇关于生成所有字母组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文