Skip to content

40. Combination Sum II #314

Answered by mah-shamim
mah-shamim asked this question in Q&A
Aug 13, 2024 · 1 comments · 2 replies
Discussion options

You must be logged in to vote

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]) {…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@basharul-siddike
Comment options

@mah-shamim
Comment options

mah-shamim Jan 23, 2025
Maintainer Author

Answer selected by basharul-siddike
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
2 participants