-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path90.SubsetsIi.cpp
69 lines (64 loc) · 1.43 KB
/
90.SubsetsIi.cpp
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
61
62
63
64
65
66
67
68
69
/*
* @lc app=leetcode id=90 lang=cpp
*
* [90] Subsets II
*
* https://leetcode.com/problems/subsets-ii/description/
*
* algorithms
* Medium (47.56%)
* Likes: 2032
* Dislikes: 91
* Total Accepted: 308K
* Total Submissions: 641K
* Testcase Example: '[1,2,2]'
*
* Given a collection of integers that might contain duplicates, nums, return
* all possible subsets (the power set).
*
* Note: The solution set must not contain duplicate subsets.
*
* Example:
*
*
* Input: [1,2,2]
* Output:
* [
* [2],
* [1],
* [1,2,2],
* [2,2],
* [1,2],
* []
* ]
*
*
*/
// @lc code=start
#include <algorithm>
#include <vector>
class Solution {
public:
std::vector<std::vector<int>> subsetsWithDup(std::vector<int>& nums) {
std::vector<int> subset;
std::vector<std::vector<int>> result;
std::sort(nums.begin(), nums.end());
dfs(nums, 0, subset, result);
return result;
}
private:
void dfs(const std::vector<int>& nums, size_t idx, std::vector<int>& subset,
std::vector<std::vector<int>>& result) {
result.push_back(subset);
if (idx >= nums.size()) {
return;
}
for (int i = idx; i < nums.size(); ++i) {
if (i != idx && nums[i] == nums[i - 1]) continue;
subset.push_back(nums[i]);
dfs(nums, i + 1, subset, result);
subset.pop_back();
}
}
};
// @lc code=end