subset ii 子集 有重复元素

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

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

思路:
Subsets这里不需要长度等于nums

.remove(tempList.size() - 1),是tempList的最后一位

一些细节:
需要排序

要求i > start

class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        //cc
        List<List<Integer>> results = new ArrayList<List<Integer>>();
        
        if (nums == null || nums.length == 0)
            return results;
        
        //排序一下
        Arrays.sort(nums);
        
        dfs(nums, new ArrayList<Integer>(), 0, results);
        
        return results;
    }
    
    public void dfs(int[] nums, List<Integer> temp, int start, 
                   List<List<Integer>> results) {
        //exit
        results.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]);
            dfs(nums, temp, i + 1, results);
            temp.remove(temp.size() - 1);
        }
 
    }
}
View Code

 




posted @ 2020-08-07 10:37  苗妙苗  阅读(148)  评论(0编辑  收藏  举报