Combinations of Coin
Problem:
Given a number of different denominations of coins (e.g., 1 cent, 5 cents, 10 cents, 25 cents), get all the possible ways to pay a target number of cents.
coins = {2, 1}, target = 4, the return should be
[0, 4], (4 cents can be conducted by 0 * 2 cents + 4 * 1 cents)
[1, 2], (4 cents can be conducted by 1 * 2 cents + 2 * 1 cents)
[2, 0] (4 cents can be conducted by 2 * 2 cents + 0 * 1 cents)
Assumptions:
Target >= 0
Coin [ ] != null
No restriction on how many coins used
There will always be a 1 coin
Solution: Recursive DFS
Base Case: When index reach 1 value coin, place remainder into it, print solution[ ]
Recursive Rule:
Branch out all valid amounts of current coin
Set solution[ ] of current coin to corresponding branch number
Call next coin with leftover money
Recursive Tree:
Implementation:
Time complexity:
For N = coin.length
O(Target^N)
Space complexity:
N levels * worst case target = O(N^T)
Last updated
Was this helpful?