To create all permutations of a given string.

Asked 2 years ago, Updated 2 years ago, 39 views

What is the best code to make all permutations of a given string? For example, if we have ba, we have ba and ab, but how do we make a program that outputs all the permutations that might come out of abcdefgh?

algorithm java

2022-09-21 18:22

1 Answers

public static void permutation(String str) { 
    permutation("", str); 
}

private static void permutation(String prefix, String str) {
    int n = str.length();
    if (n == 0) System.out.println(prefix);
    else {
        for (int i = 0; i < n; i++)
            permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
    }
}

I did it like this.


2022-09-21 18:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.