Chander Shivdasani Chander Shivdasani - 3 months ago 11
Java Question

permute a string

Given the String, print all its permutations. To do that, i came up with the following program.

public static char[] swap(char[] input, int i, int j) {
char temp;
temp = input[i];
input[i] = input[j];
input[j] = temp;

return input;

}

/**
*
* @param args
*/

public static void permuteStrings(char[] inputString, int start, int finish ) {
//Base case: When there is only single element, print the string
if(start == finish)
System.out.println(inputString);
else {
//Recursive case: Swap first element with all the elements and permute on the
// rest of string.
for(int i = start; i <= finish; i++) {
inputString = swap(inputString, start, i);
permuteStrings(inputString, i + 1, finish);
inputString = swap(inputString,start, i); //restoring the original string
}
}
}


But, for the given input ABC, all it prints are

ABC
BAC


I cant seem to figure out what the problem is

Answer

Figured out the problem. The problem was in the function invocation:

permuteStrings(inputString, i + 1, finish);.

The correct way was:

permuteStrings(inputString, start + 1, finish);