InterviewHubPRO
Section Overview
Q74

Question 74 of 100

Part 9: Backtracking & Combinatorial Search (73 - 79)

74%
DSA Patterns (Multi-Lang)•Part 9: Backtracking & Combinatorial Search (73 - 79)

Combination Sum.

In Simple Words: Backtracking with unlimited reuse: at each index $i$, either choose candidates[i] and recurse at same index $i$ (with target - candidates[i]), or skip to $i + 1$.

  • Time: $O(2^{\text{target} / \min})$ | Space: $O(\text{target} / \min)$
Multi-Language Solutions
Switch tabs or choose All
def combinationSum(candidates: list[int], target: int) -> list[list[int]]:
    res = []
    def dfs(i, curr, total):
        if total == target:
            res.append(curr.copy())
            return
        if i >= len(candidates) or total > target:
            return
        # Include candidates[i] (can reuse)
        curr.append(candidates[i])
        dfs(i, curr, total + candidates[i])
        # Skip candidates[i]
        curr.pop()
        dfs(i + 1, curr, total)
    dfs(0, [], 0)
    return res