Providing unique permutations code
Here's a concise Python function using a frequency map for backtracking to generate all unique permutations of a list with duplicates while avoiding repeated branches. It builds a frequency dictionary, then recursively constructs permutations only choosing elements with remaining count.
Below are two common ways to generate unique permutations from a multiset without producing duplicates and filtering them out after the fact.
1) Backtracking with a Frequency Map
This approach counts each distinct element, then builds permutations by choosing from the remaining counts.
Idea:
- Build a frequency dictionary
counts = {value: occurrences}.
- Use backtracking: at each step, iterate over the keys in
counts, place one element if its count is > 0, decrement that count, recurse, then restore it.
Python Example:
def unique_permutations(nums):
from collections import Counter
counts = Counter(nums)
result = []
perm = []
n = len(nums)
def backtrack():
if len(perm) == n:
result.append(perm[:])
return
for x in counts:
if counts[x] > 0:
counts[x] -= 1
perm.append(x)
backtrack()
perm.pop()
counts[x] += 1
backtrack()
return result
# Example:
# nums = [1, 1, 2]
# print(unique_permutations(nums)) -> [[1,1,2], [1,2,1], [2,1,1]]
2) Backtracking on Sorted Input (Skipping Duplicates)
If you sort the multiset first, you can skip branches that would repeat the same element at the same tree level.
Idea:
- Sort
nums.
- Track which indices are in use with a boolean array
used.
- At each recursion level, iterate through indices; if
nums[i] == nums[i-1] and nums[i-1] wasn’t used in this branch, skip nums[i].
Python Example:
def unique_permutations_sorted(nums):
nums.sort()
result = []
perm = []
used = [False] * len(nums)
def backtrack():
if len(perm) == len(nums):
result.append(perm[:])
return
for i in range(len(nums)):
# Skip if already used
if used[i]:
continue
# Skip duplicates: if same as previous and previous not used, ignore
if i > 0 and nums[i] == nums[i-1] and not used[i-1]:
continue
used[i] = True
perm.append(nums[i])
backtrack()
perm.pop()
used[i] = False
backtrack()
return result
# Example:
# nums = [1,1,2]
# print(unique_permutations_sorted(nums)) -> [[1,1,2], [1,2,1], [2,1,1]]
Both methods avoid generating duplicate permutations from the outset, rather than generating everything and filtering afterward. The frequency map approach is often simpler to reason about, while the sorted approach requires only an array and a visited mask.