KatInterview

Distinct Sub-Multisets That Hit a Target Sum

Dynamic ProgrammingAuto-graded · 24 test cases
MediumAuto-gradedDynamic Programmingbacktrackingsubset-sumduplicates

Last updated

Enumerate every distinct selection of list elements, each used at most once, that sums to a target, with negatives, zeros and duplicates allowed. Tests backtracking over value counts.

You are given a list of integers nums and an integer target. The list may contain negative numbers, zeros and repeated values.

A selection is made by choosing some of the entries of nums, where each entry may be chosen at most once. Two selections count as the same if they contain the same values with the same multiplicities. This holds even if they came from different positions in nums, and the order of the values does not matter.

Return every distinct selection whose values add up to exactly target.

Output format

  • Write each selection as a list of its values in non-decreasing order.
  • Return the selections as a list of lists, sorted in ascending lexicographic order. Compare element by element, and a list that is a proper prefix of another comes first.
  • Each distinct selection appears exactly once.
  • The empty selection [] has sum 0, so it is a valid answer when target is 0.
  • If no selection works, return an empty list [].

Constraints

  • 0 <= len(nums) <= 20
  • Values in nums and target are integers of moderate size, so ordinary Python integers are sufficient.
  • nums may contain zeros, negative numbers and duplicate values.
  • A zero can be included or left out, which gives different selections whenever one of them is valid.
  • Do not modify the input in a way that affects the caller.

Examples

Example 1

Input: distinct_selections_with_sum([2, 3, 5], 5)

Output: [[2, 3], [5]]

Example 2

Input: distinct_selections_with_sum([1, 1, 2, 2], 3)

Output: [[1, 2]]

Example 3

Input: distinct_selections_with_sum([4, -1, -3, 0], 0)

Output: [[], [-3, -1, 0, 4], [-3, -1, 4], [0]]

Example 4

Input: distinct_selections_with_sum([2, 4], 7)

Output: []

Hints

Hint 1

Selections that differ only by which equal-valued entry was picked are identical, so think in terms of distinct values and how many copies of each you take.

Hint 2

Group the list by value, sort the distinct values, and recurse over them. At each value, try taking 0, 1, ..., count copies, and record the selection when all values are processed and the remaining sum is 0.

Hint 3

Do not prune when the running sum exceeds the target, because negative numbers can bring it back. Building each selection in sorted value order and sorting the final list gives the required output order.