题目来源:https://leetcode.cn/problems/subsets-ii/description/
C++题解1:由于解集不能包含重复的子集,所以我们先对nums进行排序, 以便后续去重。
采用递归回溯法,对每个子集都即使保存,在完成第一次子集彻底的回溯后,对重复的元素进行跳过处理,因为包含它的每个子集已经存在过了,直到遇到不一样的元素,再次进行回溯。
class Solution {
public:
vector<vector<int>> res;
vector<int> sub;
void backtracking(vector<int> nums, int ind) {
res.push_back(sub);
for(int i = ind; i < nums.size(); i++) {
sub.push_back(nums[i]);
backtracking(nums, i+1);
sub.pop_back();
while(i+1 < nums.size() && nums[i] == nums[i+1]) i++;
}
return;
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
sort(nums.begin(), nums.end());
backtracking(nums, 0);
return res;
}
};
C++题解2:使用set去重。来源代码随想录
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& nums, int startIndex) {
result.push_back(path);
unordered_set<int> uset;
for (int i = startIndex; i < nums.size(); i++) {
if (uset.find(nums[i]) != uset.end()) {
continue;
}
uset.insert(nums[i]);
path.push_back(nums[i]);
backtracking(nums, i + 1);
path.pop_back();
}
}
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
result.clear();
path.clear();
sort(nums.begin(), nums.end()); // 去重需要排序
backtracking(nums, 0);
return result;
}
};