codejump
MediumPro challengePythonJavaScriptTypeScript

Backtracking — All Permutations

AlgorithmsBacktrackingRecursionArrays

nums holds distinct integers. Return every ordering of them.

Unlike subsets, order matters and every number is used: at each position, try
every number not used yet. A used array (or set) tells you which ones are
still free; mark a number before exploring and unmark it right after.

Output order (deterministic)
Permutations are listed in lexicographic order, which is what the search
produces on the sorted input when it tries smaller numbers first.

Examples

solve([1, 2, 3])  → [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
solve([0, 1])     → [[0, 1], [1, 0]]
solve([7])        → [[7]]

Constraints

  • 1 <= nums.length <= 7, values distinct, in any order.

Sample tests

Test #1The classic example
Input: [[1,2,3]]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Test #2Two numbers
Input: [[0,1]]
Output: [[0,1],[1,0]]
Test #3One number, one permutation
Input: [[7]]
Output: [[7]]