Open larscheng opened 2 months ago
回溯 题目:整数数组,包含重复,只能选一次
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> track = new LinkedList<>();
public List<List<Integer>> subsetsWithDup(int[] nums) {
//先将元素排序,确保重复元素都是连续的后面好剪枝
Arrays.sort(nums);
backtrack(nums,0);
return res;
}
private void backtrack(int[] nums, int start) {
res.add(new ArrayList<>(track));
for (int i = start; i < nums.length; i++) {
if (i > start && nums[i] == nums[i - 1]) {
//避免出现[1,2,2]中,[1,2]和[1,2]的重复现象
continue;
}
track.addLast(nums[i]);
backtrack(nums,i+1);
track.removeLast();
}
}
}
90. 子集 II
72