Algorithm to determine coin combinations

后端 未结 13 2630
臣服心动
臣服心动 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

    If you have 15, 10, 6 and 2 cents coins and you need to find how many distinct ways are there to arrive to 50 you can

    • count how many distinct ways you have to reach 50 using only 10, 6 and 2
    • count how many distinct ways you have to reach 50-15 using only 10, 6 and 2
    • count how many distinct ways you have to reach 50-15*2 using only 10, 6 and 2
    • count how many distinct ways you have to reach 50-15*3 using only 10, 6 and 2
    • Sum up all these results that are of course distinct (in the first I used no 15c coins, in the second I used one, in the third two and in the fourth three).

    So you basically can split the problem in smaller problems (possibly smaller amount and fewer coins). When you have just one coin type the answer is of course trivial (either you cannot reach the prescribed amount exactly or you can in the only possible way).

    Moreover you can also avoid repeating the same computation by using memoization, for example the number of ways of reach 20 using only [6, 2] doesn't depend if the already paid 30 have been reached using 15+15 or 10+10+10, so the result of the smaller problem (20, [6, 2]) can be stored and reused.

    In Python the implementation of this idea is the following

    cache = {}
    
    def howmany(amount, coins):
        prob = tuple([amount] + coins) # Problem signature
        if prob in cache:
            return cache[prob] # We computed this before
        if amount == 0:
            return 1 # It's always possible to give an exact change of 0 cents
        if len(coins) == 1:
            if amount % coins[0] == 0:
                return 1 # We can match prescribed amount with this coin
            else:
                return 0 # It's impossible
        total = 0
        n = 0
        while n * coins[0] <= amount:
            total += howmany(amount - n * coins[0], coins[1:])
            n += 1
        cache[prob] = total # Store in cache to avoid repeating this computation
        return total
    
    print howmany(50, [15, 10, 6, 2])
    

提交回复
热议问题