MediumNo. 0039

Combination Sum — LeetCode 39 Python Solution

Topics
Array, Backtracking
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

PythonSolution
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

Time
O(2n × n)
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
0040Combination Sum IIMedium
0216Combination Sum IIIMedium
0377Combination Sum IVMedium
0046PermutationsMedium
0047Permutations IIMedium
0051N-QueensHard

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(2n × 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.

Free to download. Check it runs on your machine, then pick a plan.