diff --git a/LeetCode/Combination Sum II.cpp b/LeetCode/Combination Sum II.cpp new file mode 100644 index 0000000..ad4bf76 --- /dev/null +++ b/LeetCode/Combination Sum II.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + vector> combinationSum2(vector& candidates, int target) { + vector> result; + vector currentCombination; + + sort(candidates.begin(), candidates.end()); + backTrack(candidates, target, 0, currentCombination, result); + return result; + } + +private: + void backTrack(vector& candidates, int target, int index, vector& currentCombination, vector>& result) { + if (target == 0) { + result.push_back(currentCombination); + return; + } + + if (target < 0) return; + + for (int i = index; i < candidates.size(); i++) { + + if (i > index && candidates[i] == candidates[i - 1]) continue; + + currentCombination.push_back(candidates[i]); + backTrack(candidates, target - candidates[i], i + 1, currentCombination, result); + currentCombination.pop_back(); + } + } +}; \ No newline at end of file