Skip to the code
cf.
+25 XP

#304 Single-Use Gift Cards

medium

A customer has gift cards with balances in cards. Several cards may have the same balance, and each card can be used at most once.

Write giftCardSets(cards, target) that returns every distinct set of balances that adds up to exactly target. Write each set sorted ascending; the sets may be listed in any order.

Two sets are the same if they use the same balances the same number of times, even if they came from different cards. Return [] if no set works.

Example 1

Input: cards = [2,5,2,1,2], target = 5
Output: [[1,2,2],[5]]

1 + 2 + 2 = 5 and 5 alone. Which 2 cards are used doesn't matter.

Example 2

Input: cards = [3,3,3], target = 6
Output: [[3,3]]

Any two of the three 3 cards give the same set.

Constraints

  • 1 <= cards.length <= 20
  • 1 <= cards[i] <= 50
  • 1 <= target <= 50
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).