LeetCode: Subsets II (subsets of array with duplicate numbers)

    // Given a collection of integers that might contain duplicates, nums, return all possible subsets.

// Note: The solution set must not contain duplicate subsets.

// For example,
// If nums = [1,2,2], a solution is:

// [
//   [2],
//   [1],
//   [1,2,2],
//   [2,2],
//   [1,2],
//   []
// ]

public class SubsetsII {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
       //handle base case
List<List<Integer>> lists = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
subsetRecursive(lists, new ArrayList<Integer> (), nums, 0);
return lists;
    }

public void subsetRecursive(List<List<Integer>> lists, List<Integer> tempList, int[] nums, int start){
lists.add(new ArrayList<>(tempList));
for(int i=start; i<nums.length; i++){
//skip duplicates
if(i>start && nums[i]==nums[i-1]) continue;
tempList.add(nums[i]);
subsetRecursive(lists, tempList, nums, i+1);
tempList.remove(tempList.size()-1);
}

}
}

No comments:

Post a Comment