KatInterview

Distinct Value Groups Summing to a Goal, Each Item Used Once

Dynamic ProgrammingAuto-graded · 20 test cases
MediumAuto-gradedDynamic Programmingbacktrackingrecursionsorting

Last updated

Enumerate every distinct multiset of values from a list with repeats that adds up to a goal, using each position at most once, via sorted backtracking with duplicate skipping.

You are given a list of positive integers values (which may contain repeated numbers) and a positive integer goal.

Find every distinct group of numbers taken from values whose sum is exactly goal.

Rules:

  • Each position in values can be used at most once. If a number appears several times in the list, a group may contain it at most that many times.
  • Two groups are considered the same if they contain the same numbers with the same counts, regardless of order. Each distinct group must appear exactly once in the answer.
  • Each group must be listed in non-decreasing order.
  • The groups themselves must be returned in lexicographic order. This is the order produced by sorting values and exploring the choices in ascending order, so a group that is a prefix of another is not an issue here because all sums equal goal and all numbers are positive.
  • If no group sums to goal, return an empty list.

Return a list of lists of integers.

Constraints

  • 0 <= len(values) <= 30 (an empty list must be handled and yields [])
  • 1 <= values[i] <= 100
  • 1 <= goal <= 500
  • The number of results may be large, so prefer a pruned backtracking search over generating every subset.

Examples

Example 1

Input: distinct_groups_with_sum([10, 1, 2, 7, 6, 1, 5], 8)

Output: [[1, 1, 6], [1, 2, 5], [1, 7], [2, 6]]

Example 2

Input: distinct_groups_with_sum([2, 5, 2, 1, 2], 5)

Output: [[1, 2, 2], [5]]

Hints

Hint 1

Sort the list first. Equal numbers become neighbors, and larger numbers come later, which makes both duplicate handling and pruning easy.

Hint 2

Write a recursive search over (start index, remaining sum). At each level, loop over candidate indices from start onward and recurse with index + 1 so no position is reused.

Hint 3

To avoid duplicate groups, skip a candidate when it equals the previous element and the index is greater than start (not greater than 0). Because the list is sorted and all numbers are positive, stop the loop entirely once a number exceeds the remaining sum.