HI, 我想基于多个字符生成字符串的所有组合.例如,如果我输入数字"5",则我的程序应生成5个字母的所有可能单词.
I want to generate all combinations of a string based on the a number of characters. For instance, if I enter the number "5" then my program should generate all the possible words with 5 letters. Please anyone can help me to start this logic?
推荐答案我有您的代码: I have YOUR code: #pragma once #include <stdio.h> #include <tchar.h> #include <malloc.h> #define AC(A) (sizeof(A)/sizeof(A[0])) const TCHAR __all_chars[] = __T("abcdefg"); int increment(unsigned int* used,const unsigned int count) { unsigned int ix; for(ix=0;(ix<count) && ((AC(__all_chars)-1)<=(++used[ix]));used[ix]=0,ix++); return ix<count; } void build(TCHAR* buff,unsigned int* used,const unsigned int count) { unsigned int ix; for(ix=0;ix<count;ix++) buff[ix] = __all_chars[used[ix]]; buff[ix] = 0; } void combine(TCHAR* buff,const unsigned int count) { unsigned int* used = (unsigned int*)malloc(sizeof(unsigned int)*count); unsigned int ix,done=0; for(ix=0;ix<count;ix++) used[ix] = 0; do { build(buff,used,count); ++done; _tprintf(__T("%04i: %s\r\n"),done,buff); } while(increment(used,count)); free(used); } int _tmain(int argc, _TCHAR* argv[]) { TCHAR s[256]; TCHAR* e; unsigned int n; if(_getts_s(s,AC(s))) { n = _tcstoul(s,&e,10); if(0<n) { TCHAR* buff = (TCHAR*)malloc(sizeof(TCHAR)*(1+n)); combine(buff,n); free(buff); } } _gettch(); return 0; }
问候.
请参阅此链接 单击 see this link Click