easy +10 pts

Permutation Generator

Generate all unique permutations of a list of distinct integers.

Implement the function `permutations(nums)` that takes a list of distinct integers (each between -100 and 100) and returns a list of all possible permutations (orderings) of those integers. The order of the permutations does not matter, but each permutation must be a list of the same length as the input, containing all original elements exactly once. The input list may be empty, in which case return `[[]]` (a list containing one empty permutation).

Constraints

0 <= len(nums) <= 8. All elements are distinct integers. The total number of permutations is at most 40320. Your solution should be efficient enough for len(nums) <= 8.

Example

>>> permutations([])
[[]]
>>> permutations([1])
[[1]]
>>> p = permutations([1,2])
>>> sorted(p)
[[1,2], [2,1]]
>>> p = permutations([1,2,3])
>>> len(p)
6
>>> sorted(p)
[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Think recursively: take the first element and insert it into all positions of permutations of the remaining elements.
Alternatively, use backtracking: swap elements to build permutations step by step.
For an empty input, return a list containing a single empty list.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.