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; + } +};