Given an integer array nums
that may contain duplicates, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order.
nums = [1,2,2]
[[],[1],[1,2],[1,2,2],[2],[2,2]]
[[]]
.import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SubsetsII {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums); // Sort to handle duplicates
backtrack(result, new ArrayList<>(), nums, 0);
return result;
}
private void backtrack(List<List<Integer>> result, List<Integer> tempList, int[] nums, int start) {
result.add(new ArrayList<>(tempList));
for (int i = start; i < nums.length; i++) {
// Skip duplicate elements
if (i > start && nums[i] == nums[i - 1]) continue;
tempList.add(nums[i]);
backtrack(result, tempList, nums, i + 1);
tempList.remove(tempList.size() - 1); // Backtrack
}
}
public static void main(String[] args) {
SubsetsII solution = new SubsetsII();
int[] nums = {1, 2, 2};
System.out.println(solution.subsetsWithDup(nums));
}
}
n
is the number of elements in nums
.2^n
subsets. However, due to duplicates, this is reduced, but the worst case is still O(2^n).This ensures we generate all possible subsets while effectively handling duplicates.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?