如何生成给定长度的字典字符串?
我正在寻找一种算法来按字典顺序生成长度为 N 的字符串(字典顺序)。例如给定长度 1,生成的字符串是:"a","b","c","d","e","f",g,h,i,j,k...,z .
对于长度 2,生成的字符串应该是:"aa","ab","ac","ad",...,"ba","bb",...,"zz"。
我们怎么能这样做?
这是我所做的:
void permute(string a, int i, int n, int length)
{
int j;
if (i == length){
string cand = a.substr(0,length);
cout<<cand<<endl;
}
else
{
for (j = i; j <= n; j++)
{
swap((a[i]), (a[j]));
permute(a, i+1,n,length);
swap((a[i]), (a[j]));
}
}
}
在调用 "permute(a,0,a.size(),1)" 时,字符串 a 如下所示:
aaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbccccccccccccccccccccddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeffffffffffffffffffffgggggggggggggggggggghhhhhhhhhhhhhhhhhhhhiiiiiiiiiiiiiiiiiiiijjjjjjjjjjjjjjjjjjjjkkkkkkkkkkkkkkkkkkkkllllllllllllllllllllmmmmmmmmmmmmmmmmmmmmnnnnnnnnnnnnnnnnnnnnooooooooooooooooooooppppppppppppppppppppqqqqqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrrrssssssssssssssssssssttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzz
生成正确的输出,但它重复字典字符串。如果我把它简化为字母,我相信像“aa”、“aaaa”这样的字符串会被遗漏。那么我们如何才能解决这个问题,有什么想法吗?