Skip to content

Commit

Permalink
Solve: Combination Sum 2
Browse files Browse the repository at this point in the history
  • Loading branch information
fkdl0048 committed Oct 8, 2024
1 parent 8d65497 commit a74de9f
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions LeetCode/Combination Sum II.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int>> result;
vector<int> currentCombination;

sort(candidates.begin(), candidates.end());
backTrack(candidates, target, 0, currentCombination, result);
return result;
}

private:
void backTrack(vector<int>& candidates, int target, int index, vector<int>& currentCombination, vector<vector<int>>& 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();
}
}
};

0 comments on commit a74de9f

Please sign in to comment.