Combination Sum — LeetCode 39 Python Solution

MediumArrayBacktracking
Problem
#39
Reading time
3 min

The problem

Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

Example

Input
candidates = [2,3,6,7], target = 7
Output
[[2,2,3],[7]]
Explanation
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.

Python solution

Python
class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        def dfs(i: int, s: int):
            if s == 0:
                ans.append(t[:])
                return
            if s < candidates[i]:
                return
            for j in range(i, len(candidates)):
                t.append(candidates[j])
                dfs(j, s - candidates[j])
                t.pop()

        candidates.sort()
        t = []
        ans = []
        dfs(0, target)
        return ans

Complexity

MeasureComplexity
TimeO(2^n \times n)
SpaceO(n) auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 39. Combination Sum is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

On study lists

This problem is on NeetCode 150, Grind 75 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 39. Combination Sum?
LeetCode 39. Combination Sum is rated Medium on LeetCode.
What is the time complexity of LeetCode 39. Combination Sum?
The Python solution on this page runs in O(2^n \times n).
What is the space complexity of LeetCode 39. Combination Sum?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 39. Combination Sum cover?
LeetCode 39. Combination Sum is tagged Array and Backtracking on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview