Subsets 系列
78. Subsets
介绍
Given a set of distinct integers, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3]
, a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
题意:求一个数组的所有子集
解答
Bit Manipulation
这种方法十分巧妙。而且也非常易于理解。对于数组中的一个元素,对于数组的任何一个子集而言,其要么在子集之中,要么不在子集之中,而不会有第三种可能性。如果将其数组中每个元素是否在子集中用一个bit位表示,
例如:对于数组[1,2,3],比特位000就表示数组中的任何一个元素都不在该子集之中,子集为空。比特位001就表示数组的3都在该子集之中,子集为3。
所以,就转换为nums.size()个比特位的排列组合。所以最后就可以转换为0到pow(2,nums.size())-1之间的数字,每个数字都单独代表着一个子集。根据数字上相应比特位上是否为1来判断是否数组中对应元素是否在集合中。
public:
vector<vector<int>> subsets(vector<int>& nums)
//Bit Manipulation
{
int n = nums.size();
int set_size = pow(2,n);
cout << set_size;
vector<vector<int>> res;
for(int i = 0; i < set_size; ++i)
{
vector<int> one;
for(int j = 0; j < n; ++j)
{
if((i >> j) & 0x01)
{
one.push_back(nums[j]);
}
}
res.push_back(one);
}
return res;
}
回溯法
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums)
//回溯法
{
vector<int> one;
vector<vector<int>> res;
helper(nums,0,res,one);
return res;
}
private:
void helper(const vector<int> &nums,int begin,vector<vector<int>> & res,vector<int> & one)
{
res.push_back(one);
for(int i = begin; i < nums.size(); ++i)
{
one.push_back(nums[i]);
helper(nums,i+1,res,one);
one.pop_back();
}
}
};
迭代法
从前往后迭代
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res;
sort(nums.begin(),nums.end());
int n = nums.size();
res.push_back(vector<int>());
for(int i = 0; i < n; ++i)
{
int m = res.size();
for(int j = 0; j < m; ++j)
{
res.push_back(res[j]);
res.back().push_back(nums[i]);
}
}
return res;
}
};
从后往前迭代。
```cpp
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res;
for(int i = nums.size()-1; i >= 0; --i)
{
int n = res.size();
for(int j = 0; j < n; ++j)
{
vector<int> temp(1,nums[i]);
copy(res[j].begin(),res[j].end(),back_inserter(temp));
res.push_back(temp);
}
vector<int> temp(1,nums[i]);
res.push_back(temp);
}
res.push_back(vector<int>());
return res;
}
};
<div class="se-preview-section-delimiter"></div>
90. Subsets II
介绍
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
<div class="se-preview-section-delimiter"></div>
解答
因为存在重复元素,Bit Manipulation方法无法使用。采用回溯法,要注意跳过重复元素。
class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
//回溯法
sort(nums.begin(),nums.end());
vector<int> one;
vector<vector<int>> res;
helper(nums,0,one,res);
return res;
}
private:
void helper(const vector<int> & nums,int begin, vector<int> & one,vector<vector<int>> & res)
{
res.push_back(one);
for(int i = begin; i < nums.size(); ++i)
{
one.push_back(nums[i]);
helper(nums,i+1,one,res);
one.pop_back();
//跳过重复元素
while(i+1 < nums.size() && nums[i+1] == nums[i])
++i;
}
}
};