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],
[2],
[2,3],
[1],
[1,3],
[1,2],
[1,2,3]
]
c++实现:
法一递归
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void dfs(const vector<int> &S, vector<int> &path, int step,vector<vector<int> > &result);
//void dfs(const vector<int> &S, vector<bool> &selected, int step,vector<vector<int> > &result);
//递归;增量构造法
vector<vector<int> > subsets(vector<int> &S)
{
sort(S.begin(), S.end()); // 输出要求有序
vector<vector<int> > result;
vector<int> path;
dfs(S, path, 0, result);
return result;
}
void dfs(const vector<int> &S, vector<int> &path, int step,vector<vector<int> > &result)
{
if (step == S.size())
{
result.push_back(path);
return;
}
// 不选S[step]
dfs(S, path, step + 1, result);
// 选S[step]
path.push_back(S[step]);
dfs(S, path, step + 1, result);
path.pop_back();
}
//递归;位向量法
//vector<vector<int> > subsets(vector<int> &S)
//{
// sort(S.begin(), S.end()); // 输出要求有序
// vector<vector<int> > result;
// vector<bool> selected(S.size(), false);
// dfs(S, selected, 0, result);
// return result;
//}
//void dfs(const vector<int> &S, vector<bool> &selected, int step,vector<vector<int> > &result)
//{
// if (step == S.size())
// {
// vector<int> subset;
// for (int i = 0; i < S.size(); i++)
// {
// if (selected[i]) subset.push_back(S[i]);
// }
// result.push_back(subset);
// return;
// }
// // 不选S[step]
// selected[step] = false;
// dfs(S, selected, step + 1, result);
// // 选S[step]
// selected[step] = true;
// dfs(S, selected, step + 1, result);
//}
int main()
{
int a[3]={1,2,3};
vector<int>vec(a,a+3);
vector<vector<int>> out;
out= subsets(vec);
vector<vector<int>>::iterator pp;
vector<int>::iterator it;
for(pp=out.begin();pp<out.end();pp++)
{
for (it=(*pp).begin();it<(*pp).end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
return 0;
}
测试结果:
法二迭代:
本方法的前提是:集合的元素不超过int 位数。用一个int 整数表示位向量,第i 位为1,则表示选择S[i],为0 则不选择。例如S={A,B,C,D},则0110=6 表示子集{B,C}。这种方法最巧妙。因为它不仅能生成子集,还能方便的表示集合的并、交、差等集合运算。设两个集合的位向量分别为B1 和B2,则B1jB2;B1&B2;B1B2 分别对应集合的并、交、对称差。
二进制法,也可以看做是位向量法,只不过更加优化。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//迭代;二进制法
vector<vector<int> > subsets(vector<int> &S)
{
sort(S.begin(), S.end()); // 输出要求有序
vector<vector<int> > result;
const size_t n = S.size();
vector<int> v;
for (size_t i = 0; i < 1 << n; i++)
{
for (size_t j = 0; j < n; j++)
{
if (i & 1 << j)
v.push_back(S[j]);
}
result.push_back(v);
v.clear();
}
return result;
}
int main()
{
int a[3]={1,2,3};
vector<int>vec(a,a+3);
vector<vector<int>> out;
out= subsets(vec);
vector<vector<int>>::iterator pp;
vector<int>::iterator it;
for(pp=out.begin();pp<out.end();pp++)
{
for (it=(*pp).begin();it<(*pp).end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
}
return 0;
}
测试结果: