This commit is contained in:
Sainnhe Park 2023-02-03 12:21:24 +08:00
parent fe6a4ec73f
commit e347731fef
2 changed files with 43 additions and 0 deletions

View File

@ -0,0 +1,14 @@
#ifndef S0090_SUBSETS_II_HPP
#define S0090_SUBSETS_II_HPP
#include <algorithm>
#include <vector>
using namespace std;
class S0090 {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums);
};
#endif

29
src/s0090_subsets_ii.cpp Normal file
View File

@ -0,0 +1,29 @@
#include "s0090_subsets_ii.hpp"
void subsetsWithDupDFS(vector<int> &subset, vector<vector<int>> &result,
vector<int> &nums, int startIndex, vector<bool> &used) {
int size = nums.size();
// 结束条件
if (startIndex == size) return;
for (int i = startIndex; i < size; ++i) {
// 剪枝,保留树枝重复
if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) continue;
subset.push_back(nums[i]);
result.push_back(subset);
used[i] = true;
subsetsWithDupDFS(subset, result, nums, i + 1, used);
used[i] = false;
subset.pop_back();
}
}
vector<vector<int>> S0090::subsetsWithDup(vector<int> &nums) {
vector<int> subset{};
vector<vector<int>> result{};
vector<bool> used(nums.size(), false);
sort(nums.begin(), nums.end());
subsetsWithDupDFS(subset, result, nums, 0, used);
result.push_back(vector<int>{});
return result;
}