forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0090-subsets-ii.cpp
34 lines (29 loc) · 965 Bytes
/
0090-subsets-ii.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
/*
Given an integer array of unique elements, return all possible subsets (the power set)
Ex. nums = [1,2,2] -> [[],[1],[1,2],[1,2,2],[2],[2,2]]
Backtracking, generate all combos, push/pop + to explore new combos, skip duplicates
Time: O(n x 2^n)
Space: O(n)
*/
class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<int> curr;
vector<vector<int>> result;
dfs(nums, 0, curr, result);
return result;
}
private:
void dfs(vector<int>& nums, int start, vector<int>& curr, vector<vector<int>>& result) {
result.push_back(curr);
for (int i = start; i < nums.size(); i++) {
if (i > start && nums[i] == nums[i - 1]) {
continue;
}
curr.push_back(nums[i]);
dfs(nums, i + 1, curr, result);
curr.pop_back();
}
}
};