Leetcode 40. Combination Sum II
Given a collection of candidate numbers (candidates
) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sum to target
.
Each number in candidates
may only be used once in the combination.
Note: The solution set must not contain duplicate combinations.
Input: candidates = [10,1,2,7,6,1,5], target = 8
Output:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
[1,7]
is the same as [7,1]
.Sort the Candidates: First, sort the candidate array to help easily skip duplicates.
Backtracking: Use a backtracking approach to explore all potential combinations.
Skip Duplicates: As we generate combinations, skip candidates that are the same as the previous candidates if they are at the same level of recursion to avoid duplicates.
Base Conditions:
#include <vector>
#include <algorithm>
class Solution {
public:
void backtrack(std::vector<int>& candidates, int target, int start, std::vector<int>& current_combination, std::vector<std::vector<int>>& result) {
if (target == 0) {
result.push_back(current_combination);
return;
}
for (int i = start; i < candidates.size() && candidates[i] <= target; ++i) {
// Skip duplicates
if (i > start && candidates[i] == candidates[i - 1]) continue;
current_combination.push_back(candidates[i]);
backtrack(candidates, target - candidates[i], i + 1, current_combination, result);
current_combination.pop_back();
}
}
std::vector<std::vector<int>> combinationSum2(std::vector<int>& candidates, int target) {
std::vector<std::vector<int>> result;
std::vector<int> current_combination;
// Sort the candidates to handle duplicates and to make it easier to stop when the sum exceeds the target.
std::sort(candidates.begin(), candidates.end());
backtrack(candidates, target, 0, current_combination, result);
return result;
}
};
This completes the problem-solving process for Combination Sum II. If there are any more questions or adjustments needed, feel free to ask!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?