Explained step by step
A permutation is each way to order the items of a group. [1] has 1; [1, 2] has 2, [1, 2] and [2, 1]; [1, 2, 3] has 6. With n distinct items there are n! permutations, that is n × (n − 1) × ... × 1. It grows very fast: with 10 items it is already 3,628,800.
If the array has repeated values, like [1, 1, 2], the previous method produces repeated permutations: choosing the first 1 or the second gives the same results. Half of the 6 come out duplicated and 3 distinct ones are left. Instead of removing repeats at the end, they are pruned earlier: in each round, each value is tried only once. For that each round uses its own hash set, duplicated, with the values already tried.
In backtracking, each permutation is a sequence of choices. For [1, 2, 3], choosing 1 first, then 3 and last 2 gives [1, 3, 2]. The options are all the items of the array, and the state is the ones chosen so far. The search forms a recursion tree: from the root, 3 rounds of choices reach a leaf, and each leaf is a permutation.
Each item can be chosen only once, so the state cannot have repeats. For that a list of booleans selected is used: selected[i] says whether choices[i] has been chosen. On choosing, it is set to True; on undoing, back to False; and the walk skips the ones already chosen. This pruning shrinks the search space from O(nⁿ) to O(n!): with 5 items, from 3,125 to 120 leaves.
selected and duplicated prune different things. selected is a single list for the whole search: it says which items are already in the state and stops the same item from appearing 2 times. duplicated is a new set in each round, in each call to backtrack: it says which values have been tried in that for loop and stops 2 equal items from being tried. In [1, 1, 2], selected prevents using the same 1 twice; duplicated prevents trying both ones in the same round.
With n distinct values there are n! permutations, and saving each one copies a list of length n, which costs O(n). The total time is O(n! × n). In memory, the recursion goes n levels deep, O(n); selected takes O(n); and there can be up to n duplicated sets at once, with up to n values each, O(n²). The total memory is O(n²).