Skip to content

Commit e924c1f

Browse files
authored
Create inverse_coin_change.py
1 parent 7530a41 commit e924c1f

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
def inverse_coin_change(amount, coins):
2+
"""
3+
Finds all combinations of coins that sum up to the given amount.
4+
5+
:param amount: Target amount
6+
:param coins: List of coin denominations
7+
:return: List of combinations (each combination is a list of coins)
8+
"""
9+
results = []
10+
11+
def backtrack(remaining, combo, start):
12+
if remaining == 0:
13+
results.append(list(combo))
14+
return
15+
for i in range(start, len(coins)):
16+
coin = coins[i]
17+
if coin <= remaining:
18+
combo.append(coin)
19+
backtrack(remaining - coin, combo, i) # allow reuse
20+
combo.pop()
21+
22+
coins.sort()
23+
backtrack(amount, [], 0)
24+
return results
25+
26+
27+
def main():
28+
import argparse
29+
30+
parser = argparse.ArgumentParser(description="Inverse Coin Change Solver")
31+
parser.add_argument("--amount", type=int, required=True, help="Target amount to reach")
32+
parser.add_argument("--coins", type=int, nargs="+", required=True, help="List of coin denominations")
33+
34+
args = parser.parse_args()
35+
36+
solutions = inverse_coin_change(args.amount, args.coins)
37+
38+
if not solutions:
39+
print(f"No combinations found to make {args.amount} using coins {args.coins}")
40+
else:
41+
print(f"Combinations to make {args.amount} using coins {args.coins}:")
42+
for combo in solutions:
43+
print(combo)
44+
45+
46+
if __name__ == "__main__":
47+
main()

0 commit comments

Comments
 (0)