题目:
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], [] ]代码如下:
#include <iostream>
#include <vector>
#include <algorithm> sort
#include <string>
using namespace std;
//iteration
class Solution1{
public:
vector<vector<int>> subsets(vector<int> &S)
{
vector<vector <int>> res(1);//加入一个空集
sort(S.begin(),S.end());
for(vector<int>::iterator itr=S.begin();itr!=S.end();itr++)
{
int size=res.size();
for(int i=0;i<size;i++)
{
res.push_back(res[i]);
res.back().push_back(*itr);
}
}
return res;
}
};
//采用位运算
class Solution2
{
public:
vector<vector<int>> subsets(vector<int> &S)
{
vector <vector<int>> res(1);
int len = S.size();
unsigned long long int bitmax = 1<<len;
unsigned long long int bit=1;
vector<int> tempset;
while (bit < bitmax)
{
tempset.clear();
int tempbit = bit;
for(int i=0; i< len;i++)
{
if(tempbit&1)
tempset.push_back(S[i]);
tempbit=tempbit>>1;
}
res.push_back(tempset);
bit++;
}
return res;
}
};
// dfs visit the sets
class Solution {
private:
vector<vector<int>> res;
public:
vector<vector<int> > subsets(vector<int> &S) {
res.clear();
sort(S.begin(),S.end());
vector<int > tmpres;
dfs(S,0,tmpres);
return res;
}
void dfs(vector<int> &S,int end,vector<int> tmpres)
{
if(end == S.size()){
res.push_back(tmpres);
return;
}
//选择该元素
tmpres.push_back(S[end]);
dfs(S,end+1,tmpres);
//不选择该元素
tmpres.pop_back();
dfs(S,end+1,tmpres);
}
};
void print(vector<vector<int>> &S)
{
for(vector<vector<int>>::iterator itr=S.begin();itr!=S.end();itr++)
{
for(int i=0;i<(*itr).size();i++)
{
cout<<(*itr)[i];
}
cout<<"\t";
}
}
int main()
{
int s[5]={0,1,2,3,4};
vector <int> str(s,s+5);
Solution solution;
cout << "S1:use the dfs to visit all the node with the two state:"<<endl;
print(solution.subsets(str));
cout <<endl<<"S2:use the iteration since the next set is based on the last set:"<<endl;
Solution1 solution1;
print(solution1.subsets(str));
cout <<endl<<"S3:use the bit to present each state of each number in the state:"<<endl;
Solution2 solution2;
print(solution2.subsets(str));
//system("PAUSE");
return 0;
}
运行结果: