...

/

Solution Review: Permutations of a String

Solution Review: Permutations of a String

This lesson provides a detailed review of the solution to the challenge of the previous lesson.

Solution: Permutations of a String

Press + to interact
class Solution {
public static void permutations(char[] array, int length) {
if (length == 1) {
System.out.println(array);
return;
}
else {
for (int i = 0; i < length; i++) {
swap(array, i, length-1);
permutations(array, length-1);
swap(array, i, length-1);
}
}
}
public static void swap(char[] array, int i, int j) {
char c;
c = array[i];
array[i] = array[j];
array[j] = c;
}
public static void main( String args[] ) {
char[] input = {'a', 'b', 'b', 'a'};
permutations(input, input.length);
}
}

Understanding the Code

Every recursive code has two methods; the recursive method and the main method.

Driver Method

The recursive method is called within the driver method. Let’s first look at what it does-from lines 25 to 27.

  • An array of characters input is initialized on line 25.

  • The recursive method permutations is called on line 26 which takes in two input parameters: ...