Given a set of distinct integers, S, return all possible subsets.
Note:
For example,
If S = [1,2,3]
, a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
class Solution { public: vector<vector<int> > subsets(vector<int> &S) { int n = S.size(); heap_sort(S); vector<vector<int>> res; for(int k=0; k<=n; k++) { vector<int> temp(k,0); get_res(-1,0,k,S,res,temp); } return res; } void get_res(int loc, int now, int k, vector<int>& s, vector<vector<int>>& res, vector<int>& temp) { if(k == now) { res.push_back(temp); return; } int n = s.size(); for(int i=loc+1; i<=n-k+now; i++) { temp[now] = s[i]; get_res(i,now+1,k,s,res,temp); } return; } void swap(vector<int>& s, int i, int j) { int t = s[i]; s[i] = s[j]; s[j] = t; } void sink(vector<int>& s, int loc, int end) { while(loc<end) { int k=2*loc+1; if(k>end) return ; if(k<end && s[k+1]>s[k]) k++; if(s[loc] > s[k]) return ; swap(s,k,loc); loc = k; } } void heap_sort(vector<int>& s) { int n = s.size()-1; for(int i=(n-1)/2; i>=0; i--) sink(s,i,n); while(n>0) { swap(s,0,n); n--; sink(s,0,n); } } };
原文地址:http://blog.csdn.net/shaya118/article/details/42672409