Permutations II
Difficulty: Medium · Pattern: Backtracking · LeetCode #47
Given nums, which may contain duplicates, return all unique permutations, in any order.
Examples
text
[1,1,2] → [[1,1,2],[1,2,1],[2,1,1]]
[1,2,3] → all 6 permutationsHints
- Use a
used[]array as in Permutations I. - To avoid duplicates, make equal values always be used in their original order: take the second
1only if the first1is already in the current path.
Approach
Sort the array. At each position, try each unused i, but skip it when:
text
i > 0 and nums[i] == nums[i-1] and not used[i-1]This means: if an equal value to the left is not in the path right now, then it was already tried at this position and has been backtracked out. Placing nums[i] here would recreate the same branch. The rule forces equal elements into a fixed relative order, so each distinct permutation is generated exactly once.
Complexity
Time: O(n · n!) worst case. Space: O(n).
Python solution
def permuteUnique(nums):
nums = sorted(nums)
res, path, used = [], [], [False] * len(nums)
def bt():
if len(path) == len(nums):
res.append(path[:])
return
for i in range(len(nums)):
if used[i] or (i > 0 and nums[i] == nums[i - 1] and not used[i - 1]):
continue
used[i] = True
path.append(nums[i])
bt()
path.pop()
used[i] = False
bt()
return resJavaScript solution
function permuteUnique(nums) {
const a = [...nums].sort((x, y) => x - y), res = [], path = [], used = new Array(a.length).fill(false);
const bt = () => {
if (path.length === a.length) { res.push([...path]); return; }
for (let i = 0; i < a.length; i++) {
if (used[i] || (i > 0 && a[i] === a[i - 1] && !used[i - 1])) continue;
used[i] = true; path.push(a[i]); bt(); path.pop(); used[i] = false;
}
};
bt();
return res;
}