开发者

Algorithm to generate all letter combinations using recursion

I remember this having a specific name, and there were example codes on various websites - but I can't remember what it was actually called so can't find anything...

Basically, I want to generate all the possible lette开发者_JAVA百科r combinations in a loop. The output would be something like this:

A
B
C
...
Z
AA
AB
AC
---
AZ
BA
BB
BC

etc...


Mathematically speaking, you are looking for the cartesian power of the alphabet.

The recursion adamk provided is correct, but you can simplify it a little:

void printAllLetterSequences(String prefix, int length) {
    System.out.println(prefix);
    if (prefix.length() < length)
        for (char c = 'A'; c <= 'Z'; c++)
            printAllLetterSequences(prefix + c, length);
}


Try this (pseudocode):

function loop(prefix, max_length):
   for c in 'A' to 'Z':
      print prefix + c

   for c in 'A' to 'Z':
      if length(prefix) < max_length:
         loop( prefix + c, max_length)

 loop('', 2 )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜