|
| 1 | +# https://leetcode.com/problems/coin-change/ |
| 2 | + |
| 3 | + |
| 4 | +# (Solution is given in Python 2) |
| 5 | + |
| 6 | +#### In the given problem , we are supposed to find minimum number of coins to get the sum equal to the amount given |
| 7 | + |
| 8 | +#### For given example |
| 9 | +# - Input : |
| 10 | + |
| 11 | +# 1. coins = [7 , 5 , 1] |
| 12 | +# 2. amount = 18 |
| 13 | + |
| 14 | +# - O/p : |
| 15 | +# 4 |
| 16 | + |
| 17 | +# We can achieve 18 by |
| 18 | +# - 2 Coins of 5 |
| 19 | +# - 1 coin of 7 |
| 20 | +# - 1 coin of 1 |
| 21 | +# - Sum = 4 |
| 22 | + |
| 23 | +# 18 can be achieved by various combinations of 7 , 5 , 1 |
| 24 | + |
| 25 | +# https://ibb.co/TtcVRYx |
| 26 | + |
| 27 | +# Refer the image above |
| 28 | + |
| 29 | +# Lets call 11 , 13 , 17 , 6 , 12 , 10 ... as subSums |
| 30 | + |
| 31 | +# As shown in the image above , 6 has been calculated previously and later on 6 is required in latter part . |
| 32 | +# Instead of computing it again , we can store the value for 6 i.e 2 (1 coin of 5 and 1 coin of 1) |
| 33 | + |
| 34 | +# As we need to store the value of recursion ie. Subsums in a memory , hence we choose DP here |
| 35 | + |
| 36 | +# Consider a list op = [] with size equal to the amount |
| 37 | + |
| 38 | +# op[] stores the number of coins required for each number from 1, 2 ,...amount |
| 39 | +# We are supposed to return op[amount] |
| 40 | + |
| 41 | +# In this case op[18] returns the minimum coins required to produce the sum 18 |
| 42 | + |
| 43 | + |
| 44 | + |
| 45 | +class Solution(object): |
| 46 | + def coinChange(self, coins, amount): |
| 47 | + """ |
| 48 | + :type coins: List[int] |
| 49 | + :type amount: int |
| 50 | + :rtype: int |
| 51 | + """ |
| 52 | + op = [amount+1] * (amount+1) |
| 53 | + op[0] = 0 |
| 54 | + for i in xrange(1, amount+1): |
| 55 | + for c in coins: |
| 56 | + if i >= c: |
| 57 | + op[i] = min(op[i], op[i-c] + 1) |
| 58 | + |
| 59 | + if op[amount] >= amount+1: |
| 60 | + return -1 |
| 61 | + return op[amount] |
| 62 | + |
| 63 | + |
0 commit comments