-
Notifications
You must be signed in to change notification settings - Fork 0
/
90. 子集 II.cc
60 lines (54 loc) · 1.58 KB
/
90. 子集 II.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums)
{
map<string, multiset<int>> memo;
backtrace(nums, 0, memo, multiset<int>());
vector<vector<int>> res;
for(auto &elem : memo)
{
vector<int> tmp;
for(auto num : elem.second)
{
tmp.push_back(num);
}
res.push_back(std::move(tmp));
}
return res;
}
void backtrace(vector<int>& nums, int index, map<string, multiset<int>> &memo, multiset<int> subres)
{
string idStr;
for(auto num : subres) idStr+=to_string(num);/* 将数组中的数字串成字符串,用于去重 */
memo[idStr] = subres;
for(int i=index; i<nums.size(); ++i)
{
auto iter = subres.insert(nums[i]);
backtrace(nums, i+1, memo, subres);
subres.erase(iter);
}
}
};
/* 优化 */
/* 排序用于去重 */
class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums)
{
vector<vector<int>> res;
sort(nums.begin(), nums.end()); /* 排序 */
backtrace(nums, 0, res, vector<int>());
return res;
}
void backtrace(vector<int>& nums, int index, vector<vector<int>> &res, vector<int> subres)
{
res.push_back(subres);
for(int i=index; i<nums.size(); ++i)
{
if(i>index && nums[i] == nums[i-1]) continue;
subres.push_back(nums[i]);
backtrace(nums, i+1, res, subres);
subres.pop_back();
}
}
};