LeetCode90 Subsets II
問題來源LeetCode90
問題描述
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],
[]
]
問題分析
這道題是LeetCode78 SubSets的延續,不過是多了一個有重複元素。一般對於有重複的元素的問題,可以考慮對數組進行排序,然後跳過重複的元素,這道題可以很簡單的用這種方式進行解決。
代碼如下
public List<List<Integer>> subsetsWithDup(int[] nums) {
result.add(new ArrayList<>());
if(nums==null||nums.length<1){
return result;
}
//對數組進行排序
Arrays.sort(nums);
help(new ArrayList<>(),0,0,nums);
return result;
}
List<List<Integer>> result = new ArrayList<>();
private void help(List<Integer> list,int from,int l,int[] nums){
if(l==nums.length){
return;
}else {
for (int i = from; i < nums.length; i++) {
if(i>from && nums[i]==nums[i-1]){
//重複的元素,跳過
continue;
}
list.add(nums[i]);
result.add(new ArrayList<>(list));
help(list,i+1,l+1,nums);
list.remove(list.size()-1);
}
}
}
LeetCode學習筆記持續更新
GitHub地址 https://github.com/yanqinghe/leetcode
CSDN博客地址 http://blog.csdn.net/yanqinghe123/article/category/7176678