0

I would like to know how to create all permutation of a given string in a recursive way.

Lets say that String a = "abcdefghijklmnopqrstxyz";.

I would like to generate a string of length 5 (for example) from a using recursion,

meaning:

  • aaaaa
  • aaaab
  • aaaba
  • aaaca
  • zabfg

Thanks in advance.

Igoranze
  • 1,506
  • 13
  • 35
Efi
  • 7
  • 4

1 Answers1

1

First, just store all the unique characters using a HashMap or so, then transfer them to a List, which we will call chars, for ease of use.

Your recursive method is building on a string. When that string reaches length 5, you are done, and you want to keep it. You can return the string or simply store it in a global list.

In this case, assume your list is called permutations.

void generatePermutation(String current) {
    if (current.length == 5) {
        permutations.add(current);
    } else {
        for (int i = 0; i < chars.size(); i++) {
            generatePermutation(current + chars.get(i));
        }
    }
}