[Leetcode 64] 78 Subsets

Problem:

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

 

Analysis:

Simple backtracking problem.

 

Code:

 1 class Solution {
 2 public:
 3     vector<vector<int> > res;
 4 
 5     vector<vector<int> > subsets(vector<int> &S) {
 6         // Start typing your C/C++ solution below
 7         // DO NOT write int main() function
 8         res.clear();
 9         sort(S.begin(), S.end());
10         vector<int> path;
11         for (int i=0; i<=S.size(); i++)
12             bc(0, path, S, i);
13         
14         return res;
15     }
16     
17     void bc(int idx, vector<int> path, vector<int> &s, int setSize) {
18         if (path.size() == setSize) {
19             res.push_back(path);
20             return ;
21         }
22         
23         for (int i=idx; i<s.size(); i++) {
24             path.push_back(s[i]);
25             bc(i+1, path, s, setSize);
26             path.pop_back();
27         }
28         
29         return ;
30     }
31 };
View Code

 

posted on 2013-05-26 14:58  freeneng  阅读(168)  评论(0编辑  收藏  举报

导航