Combination Sum
List every combination of candidates that adds up to the target, where each candidate can repeat.
The problem
You get an array candidates of distinct positive integers and an integer target. Return every unique combination of candidates that adds up to target, where each candidate may be used any number of times. Two combinations are the same when they use each number the same number of times, and the answer can be in any order.
Input candidates = [3, 4, 7], target = 10
Output [[3, 3, 4], [3, 7]]
3 + 3 + 4 = 10 uses 3 twice, and 3 + 7 = 10. No other mix of these numbers reaches 10.
Input candidates = [6, 9], target = 4
Output []
Every candidate is larger than 4, so no combination exists.
Key constraint: Every candidate is at least 2 and target is at most 40, so a combination holds at most 20 numbers and the search stays small.
How to spot the pattern
- You must list every combination that hits an exact total, not just count them.
- A number may be picked again, but [3, 7] and [7, 3] must not both appear.
The idea
Build a combination one number at a time and track how much of the target is still missing. To avoid listing the same combination twice, pick numbers in a fixed order: after choosing candidates[i], later picks may only use index i or higher. Allowing i itself again (not just i + 1) is what lets a number repeat, and when the remaining amount reaches 0, the current list is one answer.
Brute force: Try every sequence of picks in every order and remove duplicates at the end by sorting each combination, which explores the same combination many times over.
Step by step
- 1Sort
candidatesso the loop can stop as soon as a number is too big. - 2Write
backtrack(start, remaining), and save a copy ofcurrentwhenremainingis 0. - 3Loop
ifromstart, and break as soon ascandidates[i] > remaining. - 4Append
candidates[i]and callbacktrack(i, remaining - candidates[i]), so the same number can be used again. - 5Pop it afterwards and move on to the next candidate.
See the pattern move
The backtracking pattern on a small example. Step through it, or press play.
Code
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort() # lets the loop stop early once a candidate is too big
result = []
current = []
def backtrack(start: int, remaining: int) -> None:
if remaining == 0:
result.append(current.copy())
return
for i in range(start, len(candidates)):
if candidates[i] > remaining:
break # every later candidate is even bigger
current.append(candidates[i])
backtrack(i, remaining - candidates[i]) # i, not i + 1: it may repeat
current.pop()
backtrack(0, target)
return resultComplexity
Time
O(n^(t/m))
Space
O(t/m)
t is the target and m the smallest candidate, so a combination has at most t/m numbers and each level branches at most n ways; this is a loose bound, and the sorted early break cuts most branches.
Watch out for
- Recursing with
i + 1, which stops a number from being used more than once. - Looping from 0 instead of
start, which lists [3, 7] and [7, 3] as two different answers. - Sorting numbers in JavaScript with plain
sort(), which compares them as text, so 10 comes before 9.
Follow-up questions
What if each candidate can be used at most once and the input may contain duplicates?
Recurse with i + 1, sort first, and skip candidates[i] when i > start and it equals candidates[i - 1]. That is Combination Sum II.
What if you only need the number of combinations?
Use DP instead: ways[s] counts the combinations that sum to s, with the candidates in the outer loop so order doesn't matter. That is Coin Change II.
In Hinglish
Ek number lo, target mein se ghatao, aur usi index se aage badho taaki woh number dobara le sako. Remaining 0 ho gaya toh combination mil gaya; number bada ho gaya toh loop tod do.