From 832edfa6926ab9d88cb14684019618b63ce0c099 Mon Sep 17 00:00:00 2001 From: SquidSpirit Date: Thu, 27 Feb 2025 23:41:47 +0800 Subject: [PATCH] feat: 39_combination_sum_1 --- 39_combination_sum_1/main.cpp | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 39_combination_sum_1/main.cpp diff --git a/39_combination_sum_1/main.cpp b/39_combination_sum_1/main.cpp new file mode 100644 index 0000000..d3d25ab --- /dev/null +++ b/39_combination_sum_1/main.cpp @@ -0,0 +1,34 @@ +#include +using namespace std; + +class Solution { + public: + vector> combinationSum(vector& candidates, int target) { + sort(candidates.begin(), candidates.end()); + + vector> result; + + function)> recursive = [&](int target, vector chosen) { + if (target < 0) return; + + if (target == 0) { + result.emplace_back(chosen); + return; + } + + for (auto x : candidates) { + if (chosen.size() > 0 && x > chosen.back()) { + return; + } + + chosen.emplace_back(x); + recursive(target - x, chosen); + chosen.pop_back(); + } + }; + + recursive(target, {}); + + return result; + } +};