Intuition
Sort so equal values are adjacent. Backtrack picking one unused index at each depth. To avoid producing the same permutation twice, only use a duplicate value if its identical predecessor has already been used at this branch — this fixes a canonical order among equal values.
Explanation
Sort, then choose one unused slot at a time
Standard permutation backtracking picks any unused index for each position. With duplicates that generates the same permutation multiple times, so we add a de-duplication rule.
The de-duplication rule
Sort nums. When considering index i, skip it if nums[i] == nums[i-1] and nums[i-1] is not currently used (used[i-1] == false). This forces equal values to be consumed left-to-right, so each distinct multiset arrangement is built exactly once.
nums.sort()
def backtrack(path):
if len(path) == n: record path
for i in 0..n-1:
if used[i]: continue
if i > 0 and nums[i] == nums[i-1] and not used[i-1]: continue # dedupe
used[i] = true; path.push(nums[i]); backtrack(path); path.pop(); used[i] = false
Worked example
nums = [1, 1, 2] (already sorted).
- Pick index 0 (
1): then index 1 (1), then index 2 (2) →[1,1,2]. Backtrack; pick index 2 (2) then index 1 (1) →[1,2,1]. - Pick index 1 (
1) at depth 0 is skipped (nums[1]==nums[0]and index 0 unused) — that's the duplicate branch. - Pick index 2 (
2): then index 0 (1), index 1 (1) →[2,1,1].
Unique permutations: [[1,1,2], [1,2,1], [2,1,1]].
Complexity
- Time: O(n · n!) in the worst case (all distinct); far fewer with duplicates.
- Space: O(n) recursion depth.
Implementation
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
boolean[] used = new boolean[nums.length];
backtrack(nums, used, new ArrayList<>(), res);
return res;
}
private void backtrack(int[] nums, boolean[] used, List<Integer> path, List<List<Integer>> res) {
if (path.size() == nums.length) {
res.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i]) continue;
if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue;
used[i] = true;
path.add(nums[i]);
backtrack(nums, used, path, res);
path.remove(path.size() - 1);
used[i] = false;
}
}
}