78. 子集
题目
这道题也是套回溯模板,确定好每次的startIndex以及结束条件即可。
List<List<Integer>> re = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> subsets(int[] nums) {
re.add(path);
backtracking(0, nums);
return re;
}
public void backtracking(int startIndex, int[] nums){
if (startIndex == nums.length) return;
for (int i = startIndex; i < nums.length; i++){
path.add(nums[i]);
re.add(new ArrayList<>(path));
backtracking(i + 1, nums);
path.removeLast();
}
}
90. 子集 II
题目
首先要排序数组,记录上一次选择的元素,在同一层递归中的元素,选过了就不能再选,因为数组有序,就可以避免重复。
List<List<Integer>> re = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> subsetsWithDup(int[] nums) {
re.add(path);
Arrays.sort(nums);
backtracking(0, nums);
return re;
}
public void backtracking(int startIndex, int[] nums){
if (startIndex == nums.length) return;
int last = Integer.MAX_VALUE;
for (int i = startIndex; i < nums.length; i++){
if (last == nums[i]) continue;
path.add(nums[i]);
last = nums[i];
re.add(new ArrayList<>(path));
backtracking(i + 1, nums);
path.removeLast();
}
}