603. Every Ordering

A choir director has n singers, each with a different badge number listed in nums. Before the show she wants to see every possible order in which the singers could walk onto the stage in a single file.

Return all orderings as arrays of badge numbers. Each ordering must appear exactly once. The list of orderings may be in any order, but each ordering itself is read from the first singer to the last, so the order inside an ordering matters.

The expected running time is O(n * n!).

Example 1

Input:
nums = [7,2,5]
Output:
[[7,2,5],[7,5,2],[2,7,5],[2,5,7],[5,7,2],[5,2,7]]
Explanation:

Three singers can line up in 3! = 6 ways, for example [7, 2, 5] and [5, 2, 7].

Example 2

Input:
nums = [4]
Output:
[[4]]
Explanation:

One singer has exactly one ordering.

Example 3

Input:
nums = [-1,3]
Output:
[[-1,3],[3,-1]]
Explanation:

Two singers give [-1, 3] and [3, -1].

Constraints

  • 1 ≤ nums.length ≤ 5
  • -9 ≤ nums[i] ≤ 9
  • All values of nums are distinct.

How this problem is judged

Answers
The outer list may be in any order. Everything inside each item must match exactly.

Expected complexity

Time
O(n * n!)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…