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 :)