47. Permutations II
Problem
nums may contain duplicates. Return every distinct permutation, in any order.
Example: [1,1,2] → [[1,1,2],[1,2,1],[2,1,1]]
Constraints: n ≤ 8.
Sort; skip nums[i] if it equals nums[i-1] and nums[i-1] is not used — i.e. only the first copy of a value may start a branch at each depth.
Complexity: O(n · n!).
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
nums.sort()
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 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 res
assert sorted(Solution().permuteUnique([1, 1, 2])) == sorted([[1, 1, 2], [1, 2, 1], [2, 1, 1]])
assert sorted(Solution().permuteUnique([1, 2, 3])) == [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
assert Solution().permuteUnique([2, 2]) == [[2, 2]]
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
bt(nums, new boolean[nums.length], new ArrayList<>(), res);
return res;
}
private void bt(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] || (i > 0 && nums[i] == nums[i - 1] && !used[i - 1])) continue;
used[i] = true; path.add(nums[i]);
bt(nums, used, path, res);
used[i] = false; path.remove(path.size() - 1);
}
}
}
func permuteUnique(nums []int) [][]int {
sort.Ints(nums)
res, path, used := [][]int{}, []int{}, make([]bool, len(nums))
var bt func()
bt = func() {
if len(path) == len(nums) {
res = append(res, append([]int{}, path...))
return
}
for i := range nums {
// equal values are used left to right only, so each arrangement appears once
if used[i] || (i > 0 && nums[i] == nums[i-1] && !used[i-1]) {
continue
}
used[i] = true
path = append(path, nums[i])
bt()
path = path[:len(path)-1]
used[i] = false
}
}
bt()
return res
}