Leetcode#78 Subsets

原题地址

有两种方法:

1. 对于序列S,其子集可以对应为一个二进制数,每一位对应集合中的某个数字,0代表不选,1代表选,比如S={1,2,3},则子集合就是3bit的所有二进制数。

所以,照着二进制位去构造解空间即可。

2. 也可以用DFS做,对于每个元素,要么选,要么不选。

记得先排序,因为结果集的数字要从小到大出现。

代码(DFS版本):

 1 vector<vector<int> > res;
 2 
 3 void dfs(vector<int> &S, vector<int> ans, int pos) {
 4   if (pos == S.size()) {
 5     res.push_back(ans);
 6     return;
 7   }
 8   dfs(S, ans, pos + 1);
 9   ans.push_back(S[pos]);
10   dfs(S, ans, pos + 1);
11 }
12 
13 vector<vector<int> > subsets(vector<int> &S) {
14   sort(S.begin(), S.end());
15   dfs(S, vector<int>(), 0);
16   return res;
17 }
原文地址:https://www.cnblogs.com/boring09/p/4256236.html