AceYourInterviews
Checking sign-in…

121. Permutations II — Duplicates

IntermediateCanonical occurrence order removes symmetric permutation branches

Rearrange all input occurrences into every distinct value sequence. Each row must contain exactly the same multiset as the input.

Swapping two equal-valued occurrences does not create a new value permutation. Do not return repeated rows for indistinguishable arrangements.

Example 1

Input

[1,1,2]

Output

[[1,1,2],[1,2,1],[2,1,1]]

Explanation: The six labeled occurrence arrangements collapse into three value arrangements.

Example 2

Input

[4,4,4]

Output

[[4,4,4]]

Explanation: All three copies must appear in the only output row.

Example 3

Input

[]

Output

[[]]

Explanation: One empty permutation exists.

Constraints

  • 0 <= nums.length <= 9
  • -231 <= nums[i] <= 231 - 1
Hints
Hint 1

Keep a used bit for each occurrence, including equal copies.

Hint 2

Equivalent equal copies should be consumed in one canonical index order.

Hint 3

Skip a later equal occurrence while the preceding equal one is unused; emit only full paths.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

A used earlier equal copy permits the next equal copy

[1,1,2]
[[1,1,2],[1,2,1],[2,1,1]]