Subsets Series
Subsets I: http://blog.csdn.net/arcome/article/details/53888806
Subsets II: http://blog.csdn.net/Arcome/article/details/53888852
Problem
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note:
The solution set must not contain duplicate subsets.
Example
For example,
If nums = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
Algorithm
整理一下题意:给定一组整数,要求返回其所有子集。初始整数集可能包含重复,但是子集不重复。
subset I 的进化版,要求每个元素最多出现一次。
与Combination Sum II非常相似,限制条件还要少一些,基本参照Combination Sum II的框架,修改一下就可以了。
代码如下。
class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<int> temp;
vector<vector<int>> result;
sort(nums.begin(),nums.end());
generate(temp,result,nums,0);
return result;
}
void generate(vector<int> temp,vector<vector<int>>&result,vector<int> nums,int index){
result.push_back(temp);
for(int i=index;i<nums.size();i++){
if(i==index||nums[i]!=nums[i-1]){
temp.push_back(nums[i]);
generate(temp,result,nums,i+1);
temp.pop_back();
}
}
}
};
总结一下此类问题的框架。
vector<vector<int>> f(vector<int>& nums) {
vector<int> temp;
vector<vector<int>> result;
sort(nums.begin(),nums.end());
generate(temp,result,nums,0);
return result;
}
void generate(vector<int> temp,vector<vector<int>>&result,vector<int> nums,int index){
if(?){
result.push_back(temp);
return;
}
for(int i=index;i<nums.size();i++){
if(i==index||nums[i]!=nums[i-1]){ //if(?)
temp.push_back(nums[i]);
generate(temp,result,nums,i+1); //注意:此处是i+1
temp.pop_back();
}
}
}