开发者

Algorithm to generate all letter combinations using recursion

开发者 https://www.devze.com 2023-01-15 15:26 出处:网络
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...

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

精彩评论

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