Reconfiguring a string using the backtracking algorithm

I read the code below on Geeksforgeeks, but I just can't plunge into how it works! If anyone can explain this clearly. It would be great!

this is the code:

static void swap(char a[], int l, int r) {
    char temp = a[l];
    a[l] = a[r];
    a[r] = temp;
}

static void permute(char a[], int l, int r) {
    if (l == r)
        System.out.println(getString(a));
    else {
        for (int i = l; i <= r; i++) {
            swap(a, l, i);
            permute(a, l + 1, r);
            swap(a, l, i); // backtrack
        }
    }
}

enter image description here

+4
source share
1 answer

I don’t see what you are confused with: you have provided a picture that explains this quite clearly ... to me. :-)

Termination condition (bottom line of your diagram, 2 red and 1 green): if there is only one remaining element in the list, it should not be changed. The permutation is in progress. return

... , , . "" .

, : ( ) ; ( ) ;... .

- ?

+3

Source: https://habr.com/ru/post/1629277/


All Articles