Every Possible Ordering of a Set of Distinct Numbers

Implement allPermutationsOf

Given an array of distinct integers, produce every possible ordering of its elements. Unlike a subset or combination, order matters here — [5, 7, 9] and [7, 5, 9] are two different, equally valid answers. A path can be extended with any element not already placed in it; tracking "already placed" as an explicit list that gets filtered down at every node works, but rebuilds and copies that list at every single step. Swapping that out for one fixed-size array of used-flags removes the rebuilding entirely — checking or flipping a flag never depends on how many elements are left, only on marking and unmarking a single index as the recursion goes in and comes back out.

Example 1:

Input: nums = [5,7,9]

Output: [[5,7,9],[5,9,7],[7,5,9],[7,9,5],[9,5,7],[9,7,5]]

Example 2:

Input: nums = [2,4]

Output: [[2,4],[4,2]]

Example 3:

Input: nums = [8]

Output: [[8]]

+ 4 hidden test cases run on Submit.

Constraints:

  • 1 ≤ nums.length ≤ 7
  • -20 ≤ nums[i] ≤ 20, and every value in nums is distinct
  • Results are returned sorted in ascending (lexicographic) order for a stable, checkable answer

nums =

[5, 7, 9]