1

I recently learn the algorithm,today I am strained with a problem:why the swap function run twice in the string permutation recursive way? How can I understand it?Could you help me?

public class Permutation {
    public static void swap(char[] str, int i, int j) {
        char temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }

    public static void permutation(char[] str) {
        if (str==null)return;
        permutation(str,0);
    }

    private static void permutation(char[] str, int begin) {
        if (begin == str.length) {
            System.out.println(Arrays.toString(str));
        } else {
            for (int i = begin;i<str.length;i++) {
                swap(str, begin, i);
                permutation(str, begin + 1);
                swap(str, begin, i);
            }
        }
    }

    public static void main(String[] args) {
        char[] a = {'a', 'b', 'c', 'd'};
        permutation(a);
    }
}
Pisces
  • 41
  • 5
  • check this answer, especially the diagram https://stackoverflow.com/a/21843611/940923 – Alex Sep 01 '22 at 19:47

1 Answers1

3
   for (int i = begin;i<str.length;i++) {
                swap(str, begin, i);
                permutation(str, begin + 1);
                swap(str, begin, i);

This code fragment calls the next recursion level with modified string, then restores string back

MBo
  • 77,366
  • 5
  • 53
  • 86