#9 LeetCode ( Q: (90) Subsets II)
1 min readMar 26, 2020
LeetCode 90 Subsets II, Coding Interview Question
Level : Medium
Challenge : 9/1000
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],
[]
]
Solution — Java
public class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>> ();
List<Integer> item = new ArrayList<Integer>();
if(nums.length==0||nums==null)
return res;
Arrays.sort(nums);
for(int len = 1; len<= nums.length; len++)
dfs(nums,0,len,item,res);
res.add(new ArrayList<Integer>());
return res;
}
public static void dfs(int[] nums, int start, int len, List<Integer> item,List<List<Integer>> res){
if(item.size()==len){
res.add(new ArrayList<Integer>(item));
return;
}
for(int i=start; i<nums.length;i++){
item.add(nums[i]);
dfs(nums, i+1, len, item, res);
item.remove(item.size()-1);
while(i<nums.length-1&&nums[i]==nums[i+1])//skip duplicate element
i++;
}//for
}
}
Goal : 9 / 10
#stayhome