Given a set of distinct integers, S, return all possible subsets.
Note:
- Elements in a subset must be in non-descending order.
- The solution set must not contain duplicate subsets.
For example,
If S = [1,2,3]
, a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
像这种子集问题也可以用位运算来解决。
<span style="font-size:18px;">#include<iostream>
#include<vector>
#include<cstdio>
using namespace std;
void sub(int depth,vector<int> &s,vector<int> &r,vector<vector<int> > &result)
{
if(depth==s.size())//试探到了数组的末尾位置
{
result.push_back(r);
return ;
}
r.push_back(s[depth]);//取depth位置上的数
sub(depth+1,s,r,result);
r.pop_back();//不取depth位置上的数
sub(depth+1,s,r,result);
}
vector<vector<int> > subsets(vector<int> &s)
{
vector<int> r;
vector<vector<int> > result;
sub(0,s,r,result);
return result;
}
int main(int argc,char *argv[])
{
freopen("input.txt","r",stdin);
vector<int> v;
vector<vector<int> > vv;
int num,tmp;
cin>>num;
while(num--)
{
cin>>tmp;
v.push_back(tmp);
}
vv=subsets(v);
cout<<"the size of vv is:"<<vv.size()<<endl;
int vvlen=vv.size();
for(int i=0;i<vv.size();i++)
{
int vlen=vv[i].size();
for(int j=0;j<vv[i].size();j++)
cout<<vv[i][j]<<" ";
cout<<endl;
}
return 0;
}</span>