Ctrl K

Weight Sets for an Exact Load

Medium
A warehouse has weights of several kinds; their masses are listed in the array weights (all different). There is an unlimited supply of each kind. You need to balance a load of mass total: find every set of weights whose combined mass is exactly total. A set is defined by how many weights of each kind it contains, so [3, 3, 4] and [4, 3, 3] are the same set and must appear only once. Return the list of all sets. The sets, and the weights inside each set, may be listed in any order.
Example 1
weights=[4, 3, 9], total=10 → [[3, 3, 4]]

Only one set works: 3 + 3 + 4. Writing it as 4 + 3 + 3 is the same set, and no other mix of 3, 4 and 9 reaches 10.

Example 2
weights=[2, 5, 6], total=12 → [[2, 2, 2, 2, 2, 2], [2, 2, 2, 6], [2, 5, 5], [6, 6]]

Four sets: six 2s, 2 + 5 + 5, 6 + 6 and 2 + 2 + 2 + 6.

Example 3
weights=[7], total=4 → []

The only weight is heavier than the total, so there are no sets.

Constraints
  • 1 ≤ length of weights ≤ 30
  • 1 ≤ weights[i] ≤ 200
  • All values in weights are distinct
  • 1 ≤ total ≤ 500
  • There are fewer than 150 valid sets
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsCard Hands for an Exact Total MediumAll Orderings MediumDistinct Orderings With Repeats MediumEvery Topping Combo MediumWord Traced on a Letter Grid Medium
loading Python…
Input
weights=[4, 3, 9], total=10
Expected
[[3, 3, 4]]

Run checks the first 3 tests in your browser. Submit checks all 72 tests on the server, hidden ones included.