From 2729caa4e1bd4732cde519020cbe37de17249dd2 Mon Sep 17 00:00:00 2001 From: Holychung Date: Wed, 18 May 2022 22:02:56 +0800 Subject: [PATCH] Create combination-sum.cpp --- C++/combination-sum.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 C++/combination-sum.cpp diff --git a/C++/combination-sum.cpp b/C++/combination-sum.cpp new file mode 100644 index 0000000000..290da258ff --- /dev/null +++ b/C++/combination-sum.cpp @@ -0,0 +1,27 @@ +// Time: O(k * n^k) +// Space: O(k) + +class Solution { + vector> ans; + void findCombinations(vector &candidates, int begin, vector &sol, int target) { + if (target < 0) + return; + if (target == 0) { + ans.push_back(sol); + return; + } + for (int i = begin; i < candidates.size(); i++) { + sol.push_back(candidates[i]); + findCombinations(candidates, i, sol, target - candidates[i]); + sol.pop_back(); + } + } + +public: + vector> combinationSum(vector &candidates, int target) { + ans = {}; + vector sol = {}; + findCombinations(candidates, 0, sol, target); + return ans; + } +}; \ No newline at end of file