这个请好好理解i>0和i!=pos的区别,自己一开始认为是相同的效果,但其实是全然不同的
对于:[1,2,2]
前者:[[],[1],[1,2],[2]]
后者:[[],[1],[1,2],[1,2,2],[2],[2,2]]
public class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> results = new LinkedList<>();
if (nums == null || nums.length == 0) {
return results;
}
List<Integer> list = new LinkedList<>();
Arrays.sort(nums);
subsetsWithDupHelper(results, list, nums, 0);
return results;
}
private void subsetsWithDupHelper(List<List<Integer>> results, List<Integer> list, int[] nums, int pos){
results.add(new LinkedList<>(list));
for (int i = pos; i < nums.length; i++) {
//if (i > 0 && nums[i - 1] == nums[i]) {
if (i != pos && nums[i - 1] == nums[i]) {
continue;
}
list.add(nums[i]);
subsetsWithDupHelper(results, list, nums, i + 1);
list.remove(list.size() - 1);
}
}
}
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], [] ]