combination-sum.sh — zsh
arraysbacktrackingrecursion

Return unique combinations summing to target. Candidates are distinct, may be reused, and output follows input-choice DFS order.

Constraints

  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • 1 <= target <= 40

Follow-up

How does sorting enable early pruning?

Examples
Example 1
Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Example 2
Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]
Example 3
Input: candidates = [2], target = 1
Output: []
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.