Problem 598269 · medium · Level 05 Advanced Algorithms & Graphs

Weigh Out a Target, Each Weight Once

backtracking · combination sum · duplicates · pruning

A balance scale comes with a box of weights weights (positive integers, repeats allowed - two weights of 2 g are indistinguishable). You want to pick some weights whose total is exactly target, using each physical weight at most once. Return every distinct selection as a non-decreasing list, in any order, with no selection listed twice.

Examples

Input:  weights = [1, 1, 2, 5], target = 3
Output: [[1, 2]]
Explanation: using the first 1 or the second 1 gives the same selection.

Input:  weights = [2, 2, 2], target = 4
Output: [[2, 2]]

Input:  weights = [3, 4], target = 10
Output: []

Constraints

  • 0 <= len(weights) <= 12, 1 <= weights[i] <= 30
  • 0 <= target <= 60

Goals

  • Combine the forward-only index with a duplicate skip at the same level
  • Prune using a sorted candidate list
Starting Python…