40. Combination Sum II #314
-
Topics: Given a collection of candidate numbers ( Each number in Note: The solution set must not contain duplicate combinations. Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a backtracking approach. The key idea is to sort the array first to handle duplicates easily and then explore all possible combinations using backtracking. Let's implement this solution in PHP: 40. Combination Sum II <?php
function combinationSum2($candidates, $target) {
sort($candidates);
$result = [];
backtrack($candidates, $target, 0, [], $result);
return $result;
}
function backtrack($candidates, $target, $start, $currentCombination, &$result) {
if ($target == 0) {
$result[] = $currentCombination;
return;
}
for ($i = $start; $i < count($candidates); $i++) {
if ($i > $start && $candidates[$i] == $candidates[$i - 1]) {
continue; // Skip duplicates
}
if ($candidates[$i] > $target) {
break; // No need to continue if the candidate exceeds the target
}
backtrack($candidates, $target - $candidates[$i], $i + 1, array_merge($currentCombination, [$candidates[$i]]), $result);
}
}
// Example usage:
$candidates1 = [10,1,2,7,6,1,5];
$target1 = 8;
print_r(combinationSum2($candidates1, $target1));
$candidates2 = [2,5,2,1,2];
$target2 = 5;
print_r(combinationSum2($candidates2, $target2));
?> Explanation:
This code will output all unique combinations that sum up to the target while ensuring that each candidate is used only once in each combination. |
Beta Was this translation helpful? Give feedback.
We can use a backtracking approach. The key idea is to sort the array first to handle duplicates easily and then explore all possible combinations using backtracking.
Let's implement this solution in PHP: 40. Combination Sum II