思路
原题链接
- 要首先去重子集
- 和普通子集一样,在进入回溯函数的时候,就要将path加入到res中
- 然后进入for循环
- 首先执行去重,当 i > startIndex && nums[i - 1] == nums[i] 的时候,是出现重复了
- 如何理解上述语句? 假设 nums = 1 2 2 。假设已经保存了 {1,2} 此时要移除中间的2,执行removeLast,然后重新进入for循环,此时的i已经变为了2,但是startIndex还是之前的1,此时if语句里的条件就成立了,则直接continue。
- 同理当第一层for循环检测到最后一个2的时候,此时的startIndex是0,而i 是 2,此时if里面的条件也是满足的,则直接continue,避免了出现两个{2} {2}
- 可以将startIndex理解为第几层for循环的标志,当startIndex是0的时候,for循环依次从 1 2 2 开始进入下一层的循环
class Solution {
//定义全局变量res 和 path
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> subsetsWithDup( int[] nums ) {
//首先进行排序
Arrays.sort(nums);
recur(nums, 0);
return res;
}
private void recur(int[] nums, int startIndex){
//每次刚刚进入回溯的时候,就将path加入到res中
res.add(new ArrayList<>(path));
for(int i = startIndex; i < nums.length; i++){
//如下是去重语句
if(i > startIndex && nums[i - 1] == nums[i]){
continue;
}
path.addLast(nums[i]);
recur(nums, i + 1);
path.removeLast();
}
}
}