I found a recursion code in the
competitive programmer's handbook to do the same but I'm struggling to understand the logic behind it.
It states that:
Like subsets, permutations can be generated using recursion. The following function search goes through the permutations of the set {0,1,...,nĀ”1}. The function builds a vector permutation that contains the permutation, and the search begins when the function is called without parameters.
void search() {
if (permutation.size() == n) {
// process permutation
} else {
for (int i = 0; i < n; i++) {
if (chosen[i]) continue;
chosen[i] = true;
permutation.push_back(i);
search();
chosen[i] = false;
permutation.pop_back();
}
}
}
Each function call adds a new element to permutation. The array chosen indicates which elements are already included in the permutation. If the size of permutation equals the size of the set, a permutation has been generated.
I can't seem to understand the proper intuition and the concept used.
Can somemone explain me what the code is doing and what's the logic behind it?