diff --git a/include/s0090_subsets_ii.hpp b/include/s0090_subsets_ii.hpp new file mode 100644 index 0000000..0a6539d --- /dev/null +++ b/include/s0090_subsets_ii.hpp @@ -0,0 +1,14 @@ +#ifndef S0090_SUBSETS_II_HPP +#define S0090_SUBSETS_II_HPP + +#include +#include + +using namespace std; + +class S0090 { + public: + vector> subsetsWithDup(vector& nums); +}; + +#endif diff --git a/src/s0090_subsets_ii.cpp b/src/s0090_subsets_ii.cpp new file mode 100644 index 0000000..55e54b1 --- /dev/null +++ b/src/s0090_subsets_ii.cpp @@ -0,0 +1,29 @@ +#include "s0090_subsets_ii.hpp" + +void subsetsWithDupDFS(vector &subset, vector> &result, + vector &nums, int startIndex, vector &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> S0090::subsetsWithDup(vector &nums) { + vector subset{}; + vector> result{}; + vector used(nums.size(), false); + sort(nums.begin(), nums.end()); + subsetsWithDupDFS(subset, result, nums, 0, used); + result.push_back(vector{}); + return result; +}