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

DFS每次返回当前解,当解深度大于最大深度时返回。
 1 class Solution {
 2 private:
 3     vector<vector<int> > ret;
 4 public:
 5     void dfs(int dep, int maxDep, vector<int> &num, vector<int> a, int start)
 6     {
 7         ret.push_back(a);
 8         
 9         if (dep == maxDep)
10             return;
11             
12         for(int i = start; i < num.size(); i++)
13         {
14             vector<int> b(a);
15             b.push_back(num[i]);
16             dfs(dep + 1, maxDep, num, b, i + 1);
17         }
18     }
19     
20     vector<vector<int> > subsets(vector<int> &S) {
21         // Start typing your C/C++ solution below
22         // DO NOT write int main() function
23         sort(S.begin(), S.end());
24         ret.clear();
25         vector<int> a;
26         dfs(0, S.size(), S, a, 0);
27         
28         return ret;
29     }
30 };
posted @ 2012-11-15 20:24  chkkch  阅读(2060)  评论(0编辑  收藏  举报