MEDIUM NC#72 Backtracking

39. 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.

🧠 Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • Array methods (`push`, `pop`, `shift`, `slice`)
  • Object/Map/Set usage patterns
  • Function parameter and return typing
  • Recursive function frames
  • Push/pop state undo
  • Pruning branches early

Logical Thinking Concepts

  • Define invariants before coding
  • Check edge cases first (`[]`, single element, duplicates)
  • Estimate time/space before implementation
  • Apply Backtracking reasoning pattern
  • Apply Recursion reasoning pattern

💡 Approach

  • Use backtracking to try all combinations
  • Start from each candidate and recursively try adding it
  • Avoid duplicates by only moving forward in array
  • When remaining reaches 0, save current combination
  • Time: O(N^(target/min)), Space: O(N) for recursion

🛠️ Hints & Pitfalls

Hints

  • Use backtracking to try all combinations
  • Start from each candidate and recursively try adding it
  • Avoid duplicates by only moving forward in array

Common Pitfalls

  • When remaining reaches 0, save current combination
  • Time: O(N^(target/min)), Space: O(N) for recursion

🧪 Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
combinationSum([2,3,6,7], 7);
Expected:
[[2,2,3], [7]]
Test Case 2
Not run
Input:
combinationSum([2,3,5], 8);
Expected:
[[2,2,2,2], [2,3,3], [3,5]]
Test Case 3
Not run
Input:
combinationSum([2], 1);
Expected:
[]

📝 Code Editor

📚 Reference Solution

⌘K Search ⌘↩ Run ⌘S Submit