Subsets [LeetCode]

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],

  []

]

Summary: Recursive approach, we can optimize it.

 1     vector<vector<int> > subsets(vector<int> &S) {

 2         std::sort(S.begin(), S.end());

 3         vector<vector<int> > result;

 4         vector<int> subset;

 5         result.push_back(subset);

 6         if(S.size() == 0)

 7             return result;

 8         for(int i = 0; i < S.size(); i ++) {

 9             vector<int> sub_s(S.begin() + i + 1, S.end());

10             vector<vector<int> > ret = subsets(sub_s);

11             for(auto item : ret){

12                 item.insert(item.begin(), S[i]);

13                 result.push_back(item);

14             }

15         }

16         

17         return result;

18     }

 

你可能感兴趣的:(LeetCode)