题目
此题是元素存在重复的情况,可对比不存在元素重复情况的题目:78.子集
法1:DFS
经典方法,必须掌握!!!
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);
}
}