LeetCode-90 Subsets II
Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
- Elements in a subset must be in non-descending order.
- The solution set must not contain duplicate subsets.
For example,
If S = [1,2,2]
, a solution is:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
本题与上一题“Subsets”的思路相同,不过在选择元素的时候需要将同一位置重复重现的元素排除。见代码中标注的地方。
List<List<Integer>> lists = new ArrayList<List<Integer>>();
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
for(int i=0; i<=nums.length; i++) {
subsets(nums, 0, i, new ArrayList<Integer>());
}
return lists;
}
private void subsets(int[] nums, int start, int count, List<Integer> list) {
if(list.size() == count) {
lists.add(new ArrayList<Integer>(list));
} else {
for(int i=start; i<nums.length; i++) {
if(i > start && nums[i] == nums[i-1]) continue;
list.add(nums[i]);
subsets(nums, i+1, count, list);
list.remove(list.size()-1);
}
}
}
posted on 2015-02-19 19:52 linxiong1991 阅读(94) 评论(0) 编辑 收藏 举报