I have a working example to generate all char permutations in a String as below:
static ArrayList permutations(String s) {
if (s == nul
/**
*
* @param startIndex is the position of the suffix first element
* @param prefix is the prefix of the pattern
* @param suffix is the suffix of the pattern, will determine the complexity
* permute method.
*
*
* The block if (suffix.length == 1)
will print
* the only possible combination of suffix and return for computing next
* combination.
*
*
* The part after if (suffix.length == 1)
is reached if suffix
* length is not 1 that is there may be many possible combination of suffix
* therefore make a newSuffix
which will have suffix length
* (suffix.length - 1)
and recursively compute the possible
* combination of this new suffix and also the original suffix prefix
* positioned by startIndex
will change by increasing its value
* by one (startIndex + 1) % suffix.length
*
*
* T(N) = N * T(N - 1) + N
* = N! + N!(1 + 1/N + 1/(N * (N - 1)) + ... + 1/N!)
*
*
*/
public static void permute(int startIndex, int prefix[], int suffix[]) {
if (suffix.length == 1) {
for (int i = 0; i < prefix.length; i++) {
System.out.print(prefix[i] + " ");
}
System.out.print(suffix[0]);
System.out.println(" ");
return;
}
for (int i = 0; i < suffix.length; i++) {
counter++;
int newPrefix[] = new int[prefix.length + 1];
System.arraycopy(prefix, 0, newPrefix, 0, prefix.length);
newPrefix[prefix.length] = suffix[startIndex];
int newSuffix[] = new int[suffix.length - 1];
for (int j = 1; j < suffix.length; j++) {
newSuffix[j - 1] = suffix[(startIndex + j) % suffix.length];
}
permute((startIndex % newSuffix.length), newPrefix, newSuffix);
startIndex = (startIndex + 1) % suffix.length;
}
}