Choosing coins with least or no change given

前端 未结 8 1385
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-07 04:00

I am making a game which consists of coin denominations of $10, $5, $3, and $1. The player may have 0 or more of each type of currency in his inventory with a maximum of 15 coin

8条回答
  •  梦谈多话
    2021-02-07 04:39

    I had a similar problem except instead of being allowed to go over, the combination had to stay under the target amount. In the end, I used the dynamic approach presented in this answer. You should be able to use it too.

    It goes something like this:

    1. Start with a list consisting of a single empty element.
    2. For each entry in the list...
      1. Copy the entry and add to it the first coin (not coin value!) that it doesn't contain.
      2. Store the new element in the original list if and only if* its new sum value doesn't already exist in the list.
    3. Repeat step 2 until you make a pass where no new elements are added to the list
    4. Iterate the result list and keep the best combination (using your criteria)

    *: We can make this optimization because we don't particularly care which coins are used in the combination, only the sum value of the collection of coins.

    The above algorithm can be optimized a bit if you use the sum value as the key.

提交回复
热议问题