Find Subset II

topic:

Given an integer array nums that may contain repeated elements, return all possible subsets (power sets) of the array.

Note: The solution set cannot contain duplicate subsets.

Insert picture description here
Analysis:

Reference: Let's modify the subset I
: first sort the array,
and then in the recursive loop, judge whether the current number is the same as the previous number, and skip it if they are the same.
That is to say, in the case of [1,2,2,2], only the recursive loop of 0 subscript [1] and 1 subscript [2] is performed, and the 3 subscript and the subsequent ones are skipped directly.

Code:

class Solution {
    
    
    public List<List<Integer>> subsetsWithDup(int[] nums) {
    
    
    List<List<Integer>> ans = new ArrayList<>();
    Arrays.sort(nums); //排序
    getAns(nums, 0, new ArrayList<>(), ans);
    return ans;
}

private void getAns(int[] nums, int start, ArrayList<Integer> temp, List<List<Integer>> ans) {
    
    
    ans.add(new ArrayList<>(temp));
    for (int i = start; i < nums.length; i++) {
    
    
        //和上个数字相等就跳过
        if (i > start && nums[i] == nums[i - 1]) {
    
    
            continue;
        }
        temp.add(nums[i]);
        getAns(nums, i + 1, temp, ans);
        temp.remove(temp.size() - 1);
    }
}


}

Guess you like

Origin blog.csdn.net/weixin_42120561/article/details/114269261