I've got an array of integers and need to find all the possible permutations of those elements using Java. So I'll have an array at the end that contains arrays, where each one is a permutation of the original single array. It must work with any size array.
I can do this for a string, but the array is tripping me up. My elements are integers so I can't use a straightforward string method, for example, if my ints are 1, 2, 14 I would be permuting the string 1214. Would it be possible to manipulate the string and permute it, and then get my required permutations at the end by somehow filtering?
I've looked around and seem to have found a few algorithms, but practically all of them are just reams of code with little to no explanation at all so I can't understand them. Has anyone got an algorithm for this out there, an algorithm that's explained!?
Here is my algorithm for the string:
static String[] getPermutations( String str ) {
List<String> perms = new ArrayList<>();
permute( "", str, perms );
String[] list = perms.toArray( new String[ perms.size() ] );
return list;
}
// This function recursively calls itself
static void permute( String prefix, String str, List<String> perms ) {
int n = str.length();
if ( n == 0 ) {
perms.add(prefix);
} else {
for ( int i = 0; i < n; i++ ) {
permute( prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n), perms );
}
}
}