Permutations

mediumBacktrackingbacktracking with used set / swappingSolve on LeetCode#46

Part of Practice: The Big Three

Given an array of distinct integers, return every possible ordering (permutation) of its elements, in any order. For n elements there are n × (n−1) × … × 1 = n! permutations, and all of them must appear exactly once.

The array holds at most 6 elements, so the factorial-sized output is intentional and manageable.

Examples

Input:
nums = [1, 2, 3]
Output:
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

All 3! = 6 orderings of the three elements.

Input:
nums = [0, 1]
Output:
[[0, 1], [1, 0]]

Two elements have exactly two orderings.

Input:
nums = [1]
Output:
[[1]]

A single element has one trivial permutation.

Hints

One at a time — struggle first, peek second.

Your thinking space — verify on LeetCode, then mark it.