Problem:
Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: [1,2,2]
Output:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
思路:
采用的是递归的思想。每次产生新子集的时候都是由原来的所有子集添加新的数产生。
首先将数组排序(书之间的相对大小其实并不重要,只是为了将相同的数合并在一起,方便计数),然后针对每一个新的数num,统计其个数count,将其加入原来的子集中,加入的种类总共可以有count+1种(不加,加一个num,加2个num,(cdots),加count个num),就可以得到所有不重复的子集。
Solution:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<vector<int>> subsets{{}};
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size();) {
int count = 0; //用来统计某个数总共出现的次数
while (i + count < nums.size() && nums[i] == nums[i+count]) count++;
int sub_size = subsets.size();
for (int j = 0; j < sub_size; j++) {
vector<int> new_elem = subsets[j];
for (int k = 0; k < count; k++) {
new_elem.push_back(nums[i]);
subsets.push_back(new_elem);
}
}
i += count;
}
return subsets;
}
性能:
Runtime: 8 ms Memory Usage: 9.3 MB