Subsets

Problem 1:

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

Problem 2:

Given a collection of integers that might contain duplicates, 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, 2], a solution is:

[ [2], [1], [1, 2, 2], [2, 2], [1,2], [] ]

 1 class Solution {
2 public:
3     vector<vector<int> > subsets(vector<int> &S) {
4         vector<vector<int> > result;
5         vector<int> cur;
6         sort(S.begin(), S.end());
7         recursiveSubsets(result, cur, S, 0);
8         return result;
9     }
10
11     void recursiveSubsets(vector<vector<int> > &result, vector<int> &cur, const vector<int> &s, size_t idx) {
12         if(idx == s.size()) {
13             result.push_back(cur);
14         } else {
15             // do not add s[idx]
16             recursiveSubsets(result, cur, s, idx+1);
17
18             // add s[idx]
19             cur.push_back(s[idx]);
20             recursiveSubsets(result, cur, s, idx+1);
21             cur.pop_back();
22         }
23     }
24 };

 1 class Solution {
2 public:
3     vector<vector<int> > subsetsWithDup(vector<int> &S) {
4         vector<vector<int> > result;
5         vector<int> cur;
6         sort(S.begin(), S.end());
7         recursiveSubsets(result, cur, S, 0);
8         return result;
9     }
10
11     void recursiveSubsets(vector<vector<int> > &result, vector<int> &cur, const vector<int> &s, size_t idx) {
12         if(idx == s.size()) {
13             result.push_back(cur);
14         } else {
15             size_t cnt = 1;
16             size_t next = idx+1;
17             while(next < s.size() && s[next] == s[idx]) {
18                 ++cnt;
19                 ++next;
20             }
21
22             for(size_t n = 0; n <= cnt; ++n) {
23                 for(int i = 0; i < n; ++i)
24                     cur.push_back(s[idx]);
25                 recursiveSubsets(result, cur, s, next);
26                 for(int i = 0; i < n; ++i)
27                     cur.pop_back();
28             }
29         }
30     }
31 };

posted @ 2014-04-30 22:59  夏目家的猫咪老师  阅读(183)  评论(0编辑  收藏  举报