90.子集||
要求所有可能的子集,不能重复,因此对于相同的数字,要考虑去重,去重的方式就是通过排序,排序后相同的数字相邻,这样进行实现迭代时,若没有选择上一个数,,其当前数字与上一个数相同,则跳过当前生成的子集。
递归完成,撤销当前选择,继续其他选择。
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
// 满足要求的返回结构
List<List<Integer>> ans = new ArrayList<List<Integer>>();
// 先排序
Arrays.sort(nums);
// 进行迭代
backtrack(ans, new ArrayList<>(), nums, 0);
return ans;
}
private void backtrack(List<List<Integer>> ans, List<Integer> tempList, int[] nums, int start){
// 将当前子集添加到结果集中
ans.add(new ArrayList<>(tempList));
// 迭代
for (int i = start; i < nums.length; i++){
// 跳过重复元素
if (i > start && nums[i] == nums[i-1]){
continue;
}
// 更新当前子集
tempList.add(nums[i]);
// 递归
backtrack(ans, tempList, nums, i+1);
// 回溯
tempList.remove(tempList.size()-1);
}
}
}