模板题目:Backtracking/Subset( 90 Subsets II)
Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
这道题目就是非常经典的backtracking.
就是采用DFS
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
//之前的subset1是原数组里面没有重复的元素
List<List<Integer>> res = new ArrayList<>();
if(nums == null || nums.length == 0) return res;
Arrays.sort(nums);
helper(res, new ArrayList<>(), nums, 0);
return res;
}
public void helper(List<List<Integer>> res, List<Integer> list, int[] nums, int start){ //这个参数要注意 必须要有start 不然会有很多重复的
res.add(new ArrayList<>(list)); //在这儿尤其要注意 不能直接add list
for(int i = start; i< nums.length; i++){//每次从start开始
if(i != start && nums[i] == nums[i-1]) continue;//但是当i不是这个的开始 并且跟前面的一样的时候 执行剪枝操作
list.add(nums[i]);
helper(res, list, nums, i + 1);
list.remove(list.size() - 1);
}
}
}
上面的这个add / 递归函数 /remove简直就是backtracking的精华

浙公网安备 33010602011771号