Java implementation LeetCode 90 subset II (b)

90. child Collection II

Given an array of integers nums may contain duplicate elements, which returns an array of all possible subsets (power set).

Description: Solution Set can not contain duplicate subsets.

Example:

Input: [1,2,2]
Output:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]

PS:

To sort, put together to ensure that a repeating element
record length of each iteration generating a new sequence, where represents the start position of each iteration with the left, right end position, len indicates the length
depending on whether the preceding elements repeated to determine the left value, that is, traversing position

In fact, and a subset of 1 or less the same

class Solution {
      public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> retList = new ArrayList<>();
        retList.add(new ArrayList<>());
        if(nums == null || nums.length == 0) return retList;
        Arrays.sort(nums);
        
        
        List<Integer> tmp = new ArrayList<>();
        tmp.add(nums[0]);
        retList.add(tmp);
        if(nums.length == 1) return retList;
        
        int lastLen = 1;
        
        for(int i = 1; i < nums.length; i++){
            int size = retList.size();
            if(nums[i] != nums[i-1]){
                lastLen = size;
            }
            
            for(int j = size - lastLen; j < size; j++){
                List<Integer> inner = new ArrayList(retList.get(j));
                inner.add(nums[i]);
                retList.add(inner);
            }
        }
        return retList;
    }
}
Released 1206 original articles · won praise 10000 + · Views 600,000 +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104361948