From ae8598a2b154253a9f7627579eb2867ef0cc10d0 Mon Sep 17 00:00:00 2001 From: SquidSpirit Date: Fri, 28 Feb 2025 00:52:14 +0800 Subject: [PATCH] feat: 40_combination_sum_2 --- 40_combination_sum_2/main.cpp | 43 +++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 40_combination_sum_2/main.cpp diff --git a/40_combination_sum_2/main.cpp b/40_combination_sum_2/main.cpp new file mode 100644 index 0000000..15da8c1 --- /dev/null +++ b/40_combination_sum_2/main.cpp @@ -0,0 +1,43 @@ +#include +using namespace std; + +class Solution { + public: + vector> combinationSum2(vector& candidates, int target) { + vector> result; + + sort(candidates.begin(), candidates.end()); + + function, int)> recursive = [&](int target, vector chosen, int startIndex) { + if (target == 0) { + result.emplace_back(chosen); + return; + } + + for (int i = startIndex; i < candidates.size(); i++) { + int x = candidates[i]; + + if (i > startIndex && x == candidates[i - 1]) { + continue; + } + + if (target < x) return; + + chosen.emplace_back(x); + recursive(target - x, chosen, i + 1); + chosen.pop_back(); + } + }; + + recursive(target, {}, 0); + + return result; + } +}; + +int main() { + vector v{10, 1, 2, 7, 6, 1, 5}; + Solution().combinationSum2(v, 8); + + return 0; +}