题目:
代码(首刷自解 2024年2月3日):
cpp
class Solution {
private:
vector<vector<int>> res;
vector<int> path;
public:
void backtracking(vector<int>& nums, int startIndex,vector<bool> used) {
res.push_back(path);
if (startIndex > nums.size()) return;
for (int i = startIndex; i < nums.size(); ++i) {
if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
/*递归抽象成的树的同一层:若同一层的某个元素和与他相邻的
上一个元素相同则跳过该分支*/
continue;
}
path.push_back(nums[i]);
used[i] = true;
backtracking(nums, i + 1, used);
used[i] = false;
path.pop_back();
}
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<bool> used(nums.size(),0);
backtracking(nums, 0, used);
return res;
}
};