Combination Sum - 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. The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.

The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

Input & Output

Example 1 — Basic Case
$ Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
💡 Note: Two combinations sum to 7: [2,2,3] (2+2+3=7) and [7] (7=7). We can use each candidate unlimited times.
Example 2 — Multiple Solutions
$ Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]
💡 Note: Three combinations sum to 8: [2,2,2,2] (2+2+2+2=8), [2,3,3] (2+3+3=8), and [3,5] (3+5=8).
Example 3 — No Solution
$ Input: candidates = [2], target = 1
Output: []
💡 Note: No combination of [2] can sum to 1, since 2 > 1 and we need positive integers.

Constraints

  • 1 ≤ candidates.length ≤ 30
  • 2 ≤ candidates[i] ≤ 40
  • All elements of candidates are distinct
  • 1 ≤ target ≤ 40

Visualization

Tap to expand
Combination Sum: Find All Ways to Reach TargetCandidates:2367Target: 7Valid Combinations:Solution 1:2+2+3=7Solution 2:7=7Output: [[2,2,3], [7]]
Understanding the Visualization
1
Input
candidates = [2,3,6,7], target = 7
2
Process
Find all combinations summing to 7
3
Output
[[2,2,3], [7]]
Key Takeaway
🎯 Key Insight: Use backtracking to systematically explore all possible combinations while allowing unlimited reuse of candidates
Asked in
Facebook 45 Amazon 38 Google 32 Microsoft 28
78.4K Views
High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen