backtracking
arrays
sorting

Given an integer array candidates that may contain duplicate values and a non-negative integer target, return every unique non-empty combination of numbers whose sum is exactly target. Each element of candidates may be used at most once per combination, so choosing a value consumes one specific array index.

For this question, the output order is part of the contract: first sort candidates in ascending order. Then each combination must list its values in the order they were chosen during a left-to-right index scan of that sorted array. The outer answer list must follow the exact depth-first search discovery order produced by standard backtracking that, at each recursion level, tries candidate indices in increasing order starting from the current position and skips an index if it has the same value as the previous index already tried at that same recursion depth. That duplicate-skip-at-the-same-level rule is required to avoid repeated combinations, and the DFS discovery order it creates is the required canonical output order.

Input / output

  • Input: candidates: int[], target: int
  • Output: int[][] in the canonical DFS order described above

More examples

  1. candidates = [2,5,2,1,2], target = 5 returns [[1,2,2],[5]].
  2. candidates = [3,4,9], target = 2 returns [].
  3. candidates = [1,2,3], target = 0 returns [] because this bank expects only non-empty combinations and all candidate values are positive.

Constraints

  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 0 <= target <= 30

Follow-up

Once the array is sorted, how can you prune the backtracking loop early when the next candidate is already larger than the remaining target?

Examples

Example 1

Input: candidates = [10,1,2,7,6,1,5], target = 8
Output: [[1,1,6],[1,2,5],[1,7],[2,6]]

Example 2

Input: candidates = [2,5,2,1,2], target = 5
Output: [[1,2,2],[5]]

Example 3

Input: candidates = [3,4,9], target = 2
Output: []