题目
此题是元素存在重复的情况,可对比不存在元素重复情况的题目:78.子集
法1:DFS+回溯_选或不选
经典方法,必须掌握!!!
1.取第 i 个元素,那么后面一直递归下去就好了
2.不取第 i 个元素,那么后面和第 i 个元素都一样的值都需要跳过,找到第一个和 nums[i]不同的元素再递归
Python
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res, path = [], []
self.dfs(nums, 0, res, path)
return res
def dfs(self, nums, start, res, path):
if start == len(nums):
res.append(path.copy())
return
path.append(nums[start]) # 选择nums[start]
self.dfs(nums, start+1, res, path)
path.pop()
while start + 1 < len(nums) and nums[start+1] == nums[start]:
start += 1
self.dfs(nums, start+1, res, path)
Java
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> tmp = new ArrayList<>();
Arrays.sort(nums);
dfs(nums, 0, res, tmp);
return res;
}
public void dfs(int[] nums, int startIndex, List<List<Integer>> res, List<Integer> tmp) {
if (startIndex == nums.length) {
res.add(new ArrayList<>(tmp));
return;
}
tmp.add(nums[startIndex]); // 选择startIndex
dfs(nums, startIndex + 1, res, tmp);
tmp.remove(tmp.size() - 1); // 不选startIndex
while (startIndex + 1 < nums.length && nums[startIndex + 1] == nums[startIndex]) { // 如果去掉这个条件,则可解决【78.子集】
++startIndex;
}
dfs(nums, startIndex + 1, res, tmp);
}
}
使用DFS算法解决Java编程中的经典子集问题
文章介绍了如何使用深度优先搜索(DFS)算法解决Java编程中的经典问题——给定一个整数数组,找出所有可能的子集,包括重复元素。通过递归实现并利用排序优化处理相等元素
931

被折叠的 条评论
为什么被折叠?



