Distinct Value Groups Summing to a Goal, Each Item Used Once
Dynamic ProgrammingAuto-graded · 20 test casesLast 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
valuescan 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
valuesand exploring the choices in ascending order, so a group that is a prefix of another is not an issue here because all sums equalgoaland 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] <= 1001 <= 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Sort the list, then run a backtracking search whose state is (start, remaining), with a shared current path that is pushed to and popped from.
At each level, loop over indices i from start to the end and treat nums[i] as the next number in the group:
- Skip duplicates at the same level. If
i > startandnums[i] == nums[i - 1], pickingnums[i]here would rebuild exactly the groups already built fromnums[i - 1], so skip it. - Prune. If
nums[i] > remaining, every later number is at least as large, sobreak. - Choose and recurse. Append
nums[i], recurse with(i + 1, remaining - nums[i]), then pop.
When remaining == 0, store a copy of current.
Why it is correct
- Completeness: any valid group, written in sorted order, corresponds to a path that always takes the leftmost unused copy of each value. The search follows that path. Pruning only removes branches whose sum would exceed the goal, which can never recover because all numbers are positive.
- No duplicates: at one level each distinct value is tried only once (via its first occurrence), so two different paths differ at some level by a distinct value and therefore give different groups.
- Single use: recursing with
i + 1never reuses a position. The skip check usesi > start, so a repeated value is still allowed at a deeper level (for example[1, 1, 6]). - Order: sorted input with depth-first exploration in ascending order yields groups in lexicographic order, each internally sorted.
Edge cases: an empty list or a goal smaller than every element returns [], since remaining never reaches 0.
Complexity
- Time: O(2^n * n) worst case (at most 2^n groups, each copied in O(n)), though pruning reduces this considerably. Sorting adds O(n log n).
- Space: O(n) for the recursion stack and current path, excluding the output.
Reference solution
from typing import List
def distinct_groups_with_sum(values: List[int], goal: int) -> List[List[int]]:
nums = sorted(values)
result = []
current = []
def backtrack(start, remaining):
if remaining == 0:
result.append(current[:])
return
for i in range(start, len(nums)):
if i > start and nums[i] == nums[i - 1]:
continue
value = nums[i]
if value > remaining:
break
current.append(value)
backtrack(i + 1, remaining - value)
current.pop()
backtrack(0, goal)
return result