From 60117556ccf070ce717c576fd7d8325cdcb39889 Mon Sep 17 00:00:00 2001 From: smori Date: Fri, 19 Jul 2024 01:22:36 +0900 Subject: [PATCH] Add day17 --- .../Day17/215_KthLargestElementinanArray.cpp | 17 ++++++ Jongeun/Day17/40_CombinationSumII.cpp | 37 +++++++++++++ Jongeun/Day17/90_SubsetsII.cpp | 53 +++++++++++++++++++ 3 files changed, 107 insertions(+) create mode 100644 Jongeun/Day17/215_KthLargestElementinanArray.cpp create mode 100644 Jongeun/Day17/40_CombinationSumII.cpp create mode 100644 Jongeun/Day17/90_SubsetsII.cpp diff --git a/Jongeun/Day17/215_KthLargestElementinanArray.cpp b/Jongeun/Day17/215_KthLargestElementinanArray.cpp new file mode 100644 index 0000000..06d7c38 --- /dev/null +++ b/Jongeun/Day17/215_KthLargestElementinanArray.cpp @@ -0,0 +1,17 @@ +class Solution +{ +public: + int findKthLargest(vector &nums, int k) + { + priority_queue, std::less> + mq(nums.begin(), nums.end()); + + while (k > 1) + { + k--; + mq.pop(); + } + + return mq.top(); + } +}; diff --git a/Jongeun/Day17/40_CombinationSumII.cpp b/Jongeun/Day17/40_CombinationSumII.cpp new file mode 100644 index 0000000..5ceb290 --- /dev/null +++ b/Jongeun/Day17/40_CombinationSumII.cpp @@ -0,0 +1,37 @@ +class Solution +{ +public: + vector> combinationSum2(vector &candidates, int target) + { + + vector> res; + vector comb; + std::sort(candidates.begin(), candidates.end()); + _combinationSum2(res, candidates, comb, 0, target); + return res; + } + + void _combinationSum2(vector> &res, vector &candidates, vector &comb, int start, int left) + { + if (left == 0) + { + res.push_back(comb); + return; + } + else if (left < 0) + { + return; + } + + for (int i = start; i < candidates.size(); i++) + { + if (i > start && candidates[i] == candidates[i - 1]) + { + continue; + } + comb.push_back(candidates[i]); + _combinationSum2(res, candidates, comb, i + 1, left - candidates[i]); + comb.pop_back(); + } + } +}; diff --git a/Jongeun/Day17/90_SubsetsII.cpp b/Jongeun/Day17/90_SubsetsII.cpp new file mode 100644 index 0000000..0f4aebf --- /dev/null +++ b/Jongeun/Day17/90_SubsetsII.cpp @@ -0,0 +1,53 @@ +class Solution +{ +public: + vector> subsetsWithDup(vector &nums) + { + vector> res; + unordered_map m; + for (auto i : nums) + { + m[i]++; + } + + vector keys; + int steps{}; + for (auto &i : m) + { + keys.push_back(i.first); + } + + steps = keys.size(); + + vector powerSet; + _subsetsWithDup(res, powerSet, m, keys, steps); + return res; + } + + void _subsetsWithDup(vector> &res, vector &powerSet, unordered_map &m, vector &keys, int step) + { + if (step == 0) + { + res.push_back(powerSet); + return; + } + + for (int i = 0; i < m[keys[step - 1]] + 1; i++) + { + if (i == 0) + { + _subsetsWithDup(res, powerSet, m, keys, step - 1); + } + else + { + powerSet.push_back(keys[step - 1]); + _subsetsWithDup(res, powerSet, m, keys, step - 1); + } + } + + for (int i = 0; i < m[keys[step - 1]]; i++) + { + powerSet.pop_back(); + } + } +};