码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Subsets

时间:2014-12-29 22:52:49      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

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】Subsets

标签:

原文地址:http://www.cnblogs.com/reachteam/p/4192422.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!