problem:
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], [] ]
Hide Tags
Array Backtracking Bit
Manipulation
题意:给定一个数组,求出其所有的子集,包括空集
thinking:
(1)77题中已经使用DFS求出数组的指定个数为K的所有子集,这里K的取值范围为1~n,n为数组长度
具体参考:http://blog.csdn.net/hustyangju/article/details/44974825
code:
class Solution { private: vector<vector<int> > ret; vector<int> tmp; public: vector<vector<int> > subsets(vector<int> &S) { ret.clear(); unsigned int n=S.size(); if(n==0) return ret; sort(S.begin(),S.end()); tmp.clear(); ret.push_back(tmp); for(int k=1;k<=n;k++) { tmp.resize(k); dfs(0,n,S,k,0); } return ret; } protected: void dfs(int dep, int n, vector<int> &S,int k,int start) { if(dep==k) { ret.push_back(tmp); return; } for(int i=start;i<n;i++) { tmp[dep]=S[i]; dfs(dep+1,n,S,k,i+1); } } };
另一种DFS法:
class Solution { private: vector<vector<int> > ret; public: void dfs(int dep, int maxDep, vector<int> &num, vector<int> a, int start) { ret.push_back(a); if (dep == maxDep) return; for(int i = start; i < num.size(); i++) { vector<int> b(a); b.push_back(num[i]); dfs(dep + 1, maxDep, num, b, i + 1); } } vector<vector<int> > subsets(vector<int> &S) { sort(S.begin(), S.end()); ret.clear(); vector<int> a; dfs(0, S.size(), S, a, 0); return ret; } };
时间: 2024-10-26 08:22:14