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 - Optimized Backtracking INPUT candidates[] 2 3 6 7 idx: 0 1 2 3 target 7 After sorting: [2, 3, 6, 7] - Distinct integers - Unlimited reuse allowed - Find all unique combos ALGORITHM STEPS 1 Sort Candidates Enable early pruning 2 Backtrack Function Track: remain, start, path 3 Pruning Check If num > remain: break 4 Base Case remain == 0: add path Decision Tree: 7 5 -2 0 -7 3 -2 FINAL RESULT Combination 1: 2 + 2 + 3 = 7 Combination 2: 7 = 7 OUTPUT: [[2,2,3], [7]] OK - 2 valid combinations found All sums equal target 7 Key Insight: Sorting enables early termination: when a candidate exceeds remaining sum, skip all larger candidates. Using start index prevents duplicates by only considering candidates at or after current position. Same element can be reused (start stays same in recursive call). TutorialsPoint - Combination Sum | Optimized Backtracking with Sorting
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