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.

4
  • Ok, do you have a question? Commented Jun 11, 2016 at 0:10
  • This is the question...How to create the described permutations using recursion only. Commented Jun 11, 2016 at 6:20
  • Along with that solution, only print out results of length 5 Commented Jun 11, 2016 at 9:41
  • This solution is not what I'm looking for. I cannot use any for loops in this task. All other solutions that I saw in this website use for loops. Commented Jun 11, 2016 at 10:45

1 Answer 1

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));
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but I'm not allowed to use for loop, only recursion..
And I have to generate all possible permutations of length 5. In the example I gave there are 5^26 permutations.
It is impossible to do without a for loop.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.