一、题目
二、题解
相比于子集1本题中多了重复元素,相比子集1本题最重要的是去重操作,将数组元素进行排序,如果当前元素与前一个元素相同,且前一个元素在上一层中没有被使用,那么当前元素就需要被剪掉
class Solution {
public:
vector<vector<int>> res;
vector<int> path, a;
int n, check[11];
void dfs(int u) {
res.push_back(path);
for (int i = u; i < n; i++) {
if (i != 0 && a[i - 1] == a[i] && !check[i - 1]) continue;
if (!check[i]) {
path.push_back(a[i]);
check[i] = 1;
dfs(i + 1);
check[i] = 0;
path.pop_back();
}
}
}
void qsort(vector<int>& arr, int l, int r) {
if (l > r) return;
srand(time(0));
int i = l, s = l - 1, e = r + 1, x = arr[rand() % (r - l + 1) + l];
while (i < e)
if (arr[i] > x) swap(arr[i], arr[--e]);
else if (arr[i] < x) swap(arr[i++], arr[++s]);
else i++;
qsort(arr, l, s), qsort(arr, e, r);
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
a = nums;
n = a.size();
qsort(a, 0, n - 1);
dfs(0);
return res;
}
};