shriyanshi24jindal

Subsets II

Mar 30th, 2026
125
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 6.03 KB | None | 0 0
  1. class Solution {
  2. public List<List<Integer>> subsetsWithDup(int[] nums) {
  3. // sorting to skip over duplicate elements during recursion
  4. Arrays.sort(nums);
  5. List<List<Integer>> result = new ArrayList<>();
  6. List<Integer> temp = new ArrayList<>();
  7.  
  8. findSubsetsWithDuplicates(nums, 0, result, temp);
  9. return result;
  10. }
  11.  
  12. public void findSubsetsWithDuplicates(int[] nums, int index, List<List<Integer>> result, List<Integer> temp)
  13. {
  14. // base condition
  15. if(index == nums.length)
  16. {
  17. result.add(new ArrayList<>(temp));
  18. return;
  19. }
  20.  
  21.  
  22. // take the current element into the subset
  23. temp.add(nums[index]);
  24. findSubsetsWithDuplicates(nums, index+1, result, temp);
  25.  
  26. // do not take the current element into the subset
  27. temp.remove(temp.size()-1);
  28.  
  29. // Skip all duplicates of the current number
  30. while(index+1 < nums.length && nums[index] == nums[index+1])
  31. index++;
  32.  
  33. findSubsetsWithDuplicates(nums, index+1, result, temp);
  34. }
  35. }
RAW Paste Data Copied