0

You are working at the cash counter at a fun-fair, and you have different types of coins available to you in infinite quantities. The value of each coin is already given. Can you determine the number of ways of making change for a particular number of units using the given types of coins?

counter = 0
def helper(n,c):
    global counter
    if n == 0:
        counter += 1 
        return 
    if len(c) == 0:
        return

    else:
        if n >= c[0]:
            helper(n - c[0], c)
        helper(n,c[1:])

def getWays(n, c):
    helper(n,c)
    print(counter)
    return counter ```

#the helper function takes n and c 
#where 
#n is amount whose change is to be made 
#c is a list of available coins

1 Answers1

0

Let n be the amount of currency units to return as change. You wish to find N(n), the number of possible ways to return change.

One easy solution would be to first choose the "first" coin you give (let's say it has value c), then notice that N(n) is the sum of all the values N(n-c) for every possible c. Since this appears to be a recursive problem, we need some base cases. Typically, we'll have N(1) = 1 (one coin of value one).

Let's do an example: 3 can be returned as "1 plus 1 plus 1" or as "2 plus 1" (assuming coins of value one and two exist). Therefore, N(3)=2.

However, if we apply the previous algorithm, it will compute N(3) to be 3.

+------------+-------------+------------+
| First coin | Second coin | Third coin |
+------------+-------------+------------+
|      2     |      1      |            |
+------------+-------------+------------+
|            |      2      |            |
|      1     +-------------+------------+
|            |      1      |      1     |
+------------+-------------+------------+

Indeed, notice that returning 3 units as "2 plus 1" or as "1 plus 2" is counted as two different solutions by our algorithm, whereas they are the same.

We therefore need to apply an additional restriction to avoid such duplicates. One possible solution is to order the coins (for example by decreasing value). We then impose the following restriction: if at a given step we returned a coin of value c0, then at the next step, we may only return coins of value c0 or less.

This leads to the following induction relation (noting c0 the value of the coin returned in the last step): N(n) is the sum of all the values of N(n-c) for all possible values of c less than or equal to c0.

Happy coding :)

Aimery
  • 1,559
  • 1
  • 19
  • 24