Math Fundamentals18 sections · 814 units
Open in Course

Combination Sum - Implementation

The pseudocode

Here is the full solution:


function combinationSum(candidates, target)
    result := []
    backtrack(candidates, 0, [], 0, target, result)
    return result

function backtrack(candidates, start, current, sum, target, result)
    if sum = target then
        add copy of current to result
        return
    if sum > target then
        return
    for i from start to length of candidates - 1
        add candidates[i] to current
        backtrack(candidates, i, current, sum + candidates[i], target, result)
        remove last element from current

Time: O(2t)O(2^t) where tt is the target value (worst case when smallest candidate is 11). Space: O(t)O(t) for recursion depth.