【leetcode】Subsets

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 class Solution {

 2 

 3 public:

 4 

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

 6 

 7        

 8 

 9         vector<vector<int> > result;

10 

11         vector<int> tmp;

12 

13         sort(S.begin(),S.end());

14 

15         getSubset(result,S,0,tmp);

16 

17         return result;

18 

19     }

20 

21    

22 

23     void getSubset(vector<vector<int> > &result,vector<int> &S,int index,vector<int> tmp)

24 

25     {

26 

27         if(index==S.size())

28 

29         {

30 

31             result.push_back(tmp);

32 

33             return;

34 

35         }

36 

37        

38 

39         getSubset(result,S,index+1,tmp);

40 

41         tmp.push_back(S[index]);

42 

43         getSubset(result,S,index+1,tmp);

44 

45        

46 

47     }

48 

49 };

 

 

你可能感兴趣的:(LeetCode)