Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
nums = [1,2,3][[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]nums = [0,1][[0,1],[1,0]]Unlike subsets, permutations use every element exactly once, so we iterate from index 0 each time (not a start index) but skip used[i] elements. The used array prevents including the same element twice in one permutation. Backtracking resets used[i]=false to try the next choice.
Writing nested loops only works for a fixed n. Backtracking builds one position at a time for any n.
At each level, try every number that is not used yet. Mark it as used, recurse to fill the next position, then unmark it. When the path has n numbers, record it.
Permutations use a used array instead of a start index. Every unused number can go in the next position.
Run the animation above on your own input, or watch the 1:12 video explanation of Permutations with a dry run and Java code.