Distinct Sub-Multisets That Hit a Target Sum
Dynamic ProgrammingAuto-graded · 24 test casesLast 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 sum0, so it is a valid answer whentargetis0. - If no selection works, return an empty list
[].
Constraints
0 <= len(nums) <= 20- Values in
numsandtargetare integers of moderate size, so ordinary Python integers are sufficient. numsmay 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Count how many times each distinct value appears and sort the distinct values. Then run a recursion over these values. At value v with c copies available, try using 0, 1, ..., c copies. Each choice appends that many copies of v to the current selection and lowers the remaining sum by v * uses. After the last distinct value, the current selection is a valid answer exactly when the remaining sum is 0. Record a copy of it, and finally sort the results lexicographically.
Why it is correct
- Choosing a count per distinct value produces each distinct multiset exactly once. Equal values are never distinguished by position, so duplicates cannot appear.
- Values are processed in ascending order, so each selection is already non-decreasing.
- No pruning is based on the running sum exceeding the target. Negative numbers can bring the sum back, so such pruning would lose valid answers.
- Zeros are handled naturally. Taking 0, 1, ... copies of
0gives different selections, and all of them are kept when valid. - With
target == 0, the path that takes nothing ends with remaining0, so[]is included. - The final sort puts the output into the required lexicographic order.
Complexity
The number of leaves is the product of (count_i + 1) over distinct values, which is at most 2^n for n entries. The time is roughly O(2^n * n) in the worst case, including copying and the final sort. The extra space is O(n) for the recursion plus the output.
Reference solution
from collections import Counter
from typing import List
def distinct_selections_with_sum(nums: List[int], target: int) -> List[List[int]]:
counts = Counter(nums)
values = sorted(counts)
results = []
chosen = []
def search(index, remaining):
if index == len(values):
if remaining == 0:
results.append(chosen.copy())
return
value = values[index]
count = counts[value]
for uses in range(count + 1):
chosen.extend([value] * uses)
search(index + 1, remaining - value * uses)
if uses:
del chosen[-uses:]
search(0, target)
results.sort()
return results