Subsets
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
解法
先初始化为空集,再遍历数组,每次遍历都把新的数加到每个子集中,再加上之前的子集就是当前的子集
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
int len = nums.size();
vector<vector<int> > res(1);
sort(nums.begin(),nums.end());
for (int i=0;i<len;i++){
int size = res.size();
for(int j=0;j<size;j++){
res.push_back(res[j]);
res.back().push_back(nums[i]);
}
}
return res;
}
};
递归
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
int len = nums.size();
vector<vector<int> > res;
sort(nums.begin(),nums.end());
vector<int> out;
helper(nums,res,out,0);
return res;
}
void helper(vector<int>& nums, vector<vector<int> >& res, vector<int>& out, int pos){
res.push_back(out);
for (int i=pos;i<nums.size();i++){
out.push_back(nums[i]);
helper(nums,res,out,i+1);
out.pop_back();
}
}
};
参考
https://www.cnblogs.com/grandyang/p/4309345.html
Subsets II
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],
[]
]
解法1
当遍历到第一个2时,当前结果为[],[1],[2],[1,2]
当遍历到第二个2时,只需要在后面两个子集上加2,即在第一个2中新加的两个子集上加2
设置一个last 来记录上一个处理的数字,然后判定当前的数字和上面的是否相同,若不同,则循环还是从0到当前子集的个数,若相同,则新子集个数减去之前循环时子集的个数当做起点来循环,这样就不会产生重复了。
class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
if (nums.empty()) return {};
vector<vector<int>> res(1);
sort(nums.begin(), nums.end());
int size = 1, last = nums[0];
for (int i = 0; i < nums.size(); ++i) {
if (last != nums[i]) {
last = nums[i];
size = res.size();
}
int newSize = res.size();
for (int j = newSize - size; j < newSize; ++j) {
res.push_back(res[j]);
res.back().push_back(nums[i]);
}
}
return res;
}
};
递归
重点:加一句 while (i + 1 < nums.size() && nums[i] == nums[i + 1]) ++i;
class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
int len = nums.size();
vector<vector<int> > res;
sort(nums.begin(),nums.end());
vector<int> out;
helper(nums,res,out,0);
return res;
}
void helper(vector<int>& nums, vector<vector<int> >& res, vector<int>& out, int pos){
res.push_back(out);
for (int i=pos;i<nums.size();i++){
out.push_back(nums[i]);
helper(nums,res,out,i+1);
out.pop_back();
while (i + 1 < nums.size() && nums[i] == nums[i + 1]) ++i;
}
}
};