思路:
// @Title: 子集 II (Subsets II)
// @Author: qisiii
// @Date: 2024-09-20 00:28:17
// @Runtime: 1 ms
// @Memory: 42.7 MB
// @comment:
// @flag:
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>();
dfs(result, new ArrayList<>(), nums, 0);
return result;
}
private void dfs(List<List<Integer>> result, List<Integer> list, int[] nums, int start) {
result.add(new ArrayList<>(list));
if (start == nums.length) {
return;
}
HashSet<Integer> set=new HashSet<>();
//排序需要color数组,因为存在顺序,所以不能单纯的往后剪枝
//子集和组合都可以根据往后剪枝来处理
//set永远是保证单轮次不重复处理
for (int i = start; i < nums.length; i++) {
if(set.contains(nums[i])){
continue;
}else{
set.add(nums[i]);
}
list.add(nums[i]);
dfs(result, list, nums, i + 1);
list.remove(list.size() - 1);
}
}
}
思路:
// @Title: 子集 II (Subsets II)
// @Author: qisiii
// @Date: 2024-09-22 00:25:28
// @Runtime: 1 ms
// @Memory: 42.5 MB
// @comment:
// @flag:
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
//排序是针对的向后剪枝方案的去重
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>();
dfs(result, new ArrayList<>(), nums, 0);
return result;
}
private void dfs(List<List<Integer>> result, List<Integer> list, int[] nums, int start) {
result.add(new ArrayList<>(list));
if (start == nums.length) {
return;
}
HashSet<Integer> set=new HashSet<>();
//排序需要color数组,因为存在顺序,所以不能单纯的往后剪枝
//子集和组合都可以根据往后剪枝来处理
//set永远是保证单轮次不重复处理
for (int i = start; i < nums.length; i++) {
if(set.contains(nums[i])){
continue;
}else{
set.add(nums[i]);
}
list.add(nums[i]);
dfs(result, list, nums, i + 1);
list.remove(list.size() - 1);
}
}
}
思路:
// @Title: 子集 II (Subsets II)
// @Author: qisiii
// @Date: 2024-09-20 00:29:12
// @Runtime: 1 ms
// @Memory: 42.5 MB
// @comment:
// @flag:
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
//排序是针对的向后剪枝方案的去重
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>();
dfs(result, new ArrayList<>(), nums, 0);
return result;
}
private void dfs(List<List<Integer>> result, List<Integer> list, int[] nums, int start) {
result.add(new ArrayList<>(list));
if (start == nums.length) {
return;
}
HashSet<Integer> set=new HashSet<>();
//排序需要color数组,因为存在顺序,所以不能单纯的往后剪枝
//子集和组合都可以根据往后剪枝来处理
//set永远是保证单轮次不重复处理
for (int i = start; i < nums.length; i++) {
if(set.contains(nums[i])){
continue;
}else{
set.add(nums[i]);
}
list.add(nums[i]);
dfs(result, list, nums, i + 1);
list.remove(list.size() - 1);
}
}
}