Subsets II

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>> subsetsWithDup(vector<int> &S) {
 4         vector<vector<int> > res(1, vector<int>());
 5         sort(S.begin(), S.end());
 6         vector<int> set;
 7         int N = S.size();
 8         for (int l = 1; l <= N; ++l)
 9             subsetsWithDupRe(S, l, 0, set, res);
10         return res;
11     }
12 
13     void subsetsWithDupRe(vector<int> &S, int L, int start, vector<int> &set, vector<vector<int>> &res)
14     {
15         int N = S.size(), M = set.size();
16         if (M == L) {
17             res.push_back(set);
18             return;
19         }
20         for (int i = start; i <= N - (L - M); ++i) {
21             if (i > start && S[i] == S[i-1]) continue; // important determint
22             set.push_back(S[i]);
23             subsetsWithDupRe(S, L, i + 1, set, res);
24             set.pop_back();
25         }
26     }
27 };

 

posted @ 2014-04-04 23:01  beehard  阅读(124)  评论(0编辑  收藏  举报