From e347731fef427fc9e3ce29e25249a35388e08127 Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Fri, 3 Feb 2023 12:21:24 +0800 Subject: [PATCH] s0090 --- include/s0090_subsets_ii.hpp | 14 ++++++++++++++ src/s0090_subsets_ii.cpp | 29 +++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 include/s0090_subsets_ii.hpp create mode 100644 src/s0090_subsets_ii.cpp 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; +}