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], [] ]
思路
递归
1 vector<vector<int> > result; 2 vector<int> tmp; 3 void initialize(vector<int> &S){ 4 tmp.clear(); 5 result.clear(); 6 int n = S.size(); 7 int i,j; 8 int t; 9 for(i = 0; i < n-1; i++){ 10 for(j = 0; j <= n-2-i; j++){ 11 if(S[j] > S[j+1]){ 12 t = S[j]; 13 S[j] = S[j+1]; 14 S[j+1] = t; 15 } 16 } 17 } 18 } 19 void getSubsets(vector<int> &S, int start, int end){ 20 if(end == start){ 21 result.push_back(tmp); 22 return; 23 } 24 getSubsets(S, start+1, end); 25 tmp.push_back(S[start]); 26 getSubsets(S, start+1, end); 27 tmp.pop_back(); 28 } 29 vector<vector<int> > subsets(vector<int> &S) { 30 // Note: The Solution object is instantiated only once and is reused by each test case. 31 int n = S.size(); 32 initialize(S); 33 getSubsets(S, 0, n); 34 return result; 35 }