Example code
This example shows how to count the number of ways to make change:How it works
The recursive solution uses the include/exclude pattern:-
Base cases:
- If
amount == 0: One way to make change (use no coins) - If
amount < 0: No valid way - If no coins left but amount remains: No valid way
- If
-
Recursive cases:
- Include: Use the current coin, subtract its value from amount
- Exclude: Don’t use the current coin, move to next coin
- Return the sum of both possibilities
For amount=5 and coins=[1, 2, 5], there are 4 ways to make change:
- 5 (one 5-cent coin)
- 2 + 2 + 1 (two 2-cent coins and one 1-cent coin)
- 2 + 1 + 1 + 1 (one 2-cent coin and three 1-cent coins)
- 1 + 1 + 1 + 1 + 1 (five 1-cent coins)
Decorator configuration
The@vs decorator is configured to improve visualization:
ignore_args=["coins"]: Hides the coins array from tree nodes (since it doesn’t change)show_argument_name=False: Shows only values without parameter names for cleaner nodes
amount and n).
Output
Running this code generates:- Console output:
4(the number of ways to make 5 cents) - Animation file:
coin_change.gifshowing the complete recursion tree with a 3-second delay between frames