Ctrl K

Card Hands for an Exact Total

Medium
Some cards lie on the table, each with a number on it; the values are listed in the array cards and may repeat. You need to build a **hand**: a few cards whose numbers add up to exactly total. Each card on the table can be taken at most once. Hands are compared by their values: if two hands consist of the same numbers (even if they use different physical cards), they are the same hand and must appear exactly once in the answer. Return all distinct hands. The hands, and the numbers inside each hand, may be listed in any order.
Example 1
cards=[3, 1, 4, 2, 3], total=6 → [[1, 2, 3], [2, 4], [3, 3]]

The hands 1 + 2 + 3, 2 + 4 and 3 + 3 work. There are two 3s, but the hand 1 + 2 + 3 counts once, whichever 3 you take.

Example 2
cards=[5, 5, 5], total=10 → [[5, 5]]

The only hand is two 5s.

Example 3
cards=[4, 8], total=6 → []

No hand adds up to 6, so the answer is empty.

Constraints
  • 1 ≤ length of cards ≤ 100
  • 1 ≤ cards[i] ≤ 50
  • 1 ≤ total ≤ 30
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsWeight Sets for an Exact Load MediumAll Orderings MediumDistinct Orderings With Repeats MediumEvery Topping Combo MediumWord Traced on a Letter Grid Medium
loading Python…
Input
cards=[3, 1, 4, 2, 3], total=6
Expected
[[1, 2, 3], [2, 4], [3, 3]]

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