90. Subsets II
Problem
nums may contain duplicates. Return every distinct subset, in any order, without listing the same subset twice.
Example: [1,2,2] → [[],[1],[1,2],[1,2,2],[2],[2,2]]
Constraints: n ≤ 10.
Sort; at the same depth skip a value equal to its left neighbour (i > start), so each distinct choice branches once.
Complexity: O(n · 2ⁿ).
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res, path = [], []
def bt(start):
res.append(path[:])
for i in range(start, len(nums)):
if i > start and nums[i] == nums[i - 1]:
continue
path.append(nums[i])
bt(i + 1)
path.pop()
bt(0)
return res
assert sorted(map(sorted, Solution().subsetsWithDup([1, 2, 2]))) == sorted(map(sorted, [[], [1], [1, 2], [1, 2, 2], [2], [2, 2]]))
assert sorted(map(sorted, Solution().subsetsWithDup([0]))) == [[], [0]]
assert sorted(map(sorted, Solution().subsetsWithDup([4, 4, 1, 4]))) == [[], [1], [1, 4], [1, 4, 4], [1, 4, 4, 4], [4], [4, 4], [4, 4, 4]]
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
bt(nums, 0, new ArrayList<>(), res);
return res;
}
private void bt(int[] nums, int start, List<Integer> path, List<List<Integer>> res) {
res.add(new ArrayList<>(path));
for (int i = start; i < nums.length; i++) {
if (i > start && nums[i] == nums[i - 1]) continue;
path.add(nums[i]);
bt(nums, i + 1, path, res);
path.remove(path.size() - 1);
}
}
}
func subsetsWithDup(nums []int) [][]int {
sort.Ints(nums)
res, path := [][]int{}, []int{}
var bt func(start int)
bt = func(start int) {
res = append(res, append([]int{}, path...))
for i := start; i < len(nums); i++ {
if i > start && nums[i] == nums[i-1] { // same value at the same depth: skip
continue
}
path = append(path, nums[i])
bt(i + 1)
path = path[:len(path)-1]
}
}
bt(0)
return res
}