Algorithm to determine coin combinations

后端 未结 13 2613
臣服心动
臣服心动 2020-12-25 08:33

I was recently faced with a prompt for a programming algorithm that I had no idea what to do for. I\'ve never really written an algorithm before, so I\'m kind of a newb at t

13条回答
  •  旧巷少年郎
    2020-12-25 09:05

    This seems somewhat like a Partition, except that you don't use all integers in 1:50. It also seems similar to bin packing problem with slight differences:

    • Wikipedia: Partition (Number Theory)
    • Wikipedia: Bin packing problem
    • Wolfram Mathworld: Partiton

    Actually, after thinking about it, it's an ILP, and thus NP-hard.

    I'd suggest some dynamic programming appyroach. Basically, you'd define a value "remainder" and set it to whatever your goal was (say, 50). Then, at every step, you'd do the following:

    1. Figure out what the largest coin that can fit within the remainder
    2. Consider what would happen if you (A) included that coin or (B) did not include that coin.
    3. For each scenario, recurse.

    So if remainder was 50 and the largest coins were worth 25 and 10, you'd branch into two scenarios:

    1. Remainder = 25, Coinset = 1x25
    2. Remainder = 50, Coinset = 0x25
    

    The next step (for each branch) might look like:

    1-1. Remainder = 0,  Coinset = 2x25 <-- Note: Remainder=0 => Logged
    1-2. Remainder = 25, Coinset = 1x25
    2-1. Remainder = 40, Coinset = 0x25, 1x10
    2-2. Remainder = 50, Coinset = 0x25, 0x10
    

    Each branch would split into two branches unless:

    • the remainder was 0 (in which case you would log it)
    • the remainder was less than the smallest coin (in which case you would discard it)
    • there were no more coins left (in which case you would discard it since remainder != 0)

提交回复
热议问题