Leetcode: Subsets

题目:

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;


}

运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值