Show problems as
Classic problem #47MediumArrayBacktrackingSorting

Permutations II

Real-world version: Distinct Step Orders
Tracked in this browser only
Read Permutations II on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A bench replays a batch of calibration steps, one after another. The batch is given as steps, a list of signed millivolt values that may contain repeats.

A read-out is the sequence of numbers the bench prints when it plays every entry of the batch exactly once, honouring repeats: a value appearing twice in steps is printed twice. Two read-outs are the same when they print the same numbers in the same order, so rearranging entries that hold equal values does not produce a new read-out.

Return every distinct read-out. The read-outs may be returned in any order.

Examples

Example 1

Input
steps = [2,1,2]
Output
[[1,2,2],[2,1,2],[2,2,1]]

Each read-out prints both 2s and the single 1, and there are three ways the 1 can sit relative to the pair of 2s.

Example 2

Input
steps = [-1,0,-1]
Output
[[-1,-1,0],[-1,0,-1],[0,-1,-1]]

The batch holds two copies of -1 and one 0, so the distinct read-outs are the three placements of the 0.

Constraints

  • 1 <= steps.length <= 8
  • -10 <= steps[i] <= 10

The values you return may be in any order.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def distinct_step_orders(steps: list[int]) -> list[list[int]]:
Java
public List<List<Integer>> distinctStepOrders(int[] steps)