-
Notifications
You must be signed in to change notification settings - Fork 0
/
CoinChange.py
53 lines (45 loc) · 1.34 KB
/
CoinChange.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
coins = [1,3,4,5]
amount = 7
def getMinCoins(coins, amount):
if amount < 0:
return -1
if amount == 0:
return 0
res = float('inf')
for coin in coins:
subResult = getMinCoins(coins, amount-coin)
if subResult >= 0 and subResult < res:
res = subResult + 1
return -1 if res == float('inf') else res
def getMinCoins(coins, amount):
dp = [amount+1] * (amount+1)
dp[0] = 0
for amt in range(1, amount+1):
for c in coins:
if amt-c >= 0:
dp[amt] = min(dp[amt], 1+dp[amt-c])
return dp[-1]
def getMinCoinsArray(coins, amount):
res = []
def recur(i, currentCoins, total):
if total>amount:
return
if total == amount:
if not res or len(currentCoins) < len(res[0]):
while res:
res.pop()
res.append(currentCoins.copy())
elif len(res[-1]) == len(currentCoins):
res.append(currentCoins.copy())
return
for i in range(len(coins)):
currentCoins.append(coins[i])
recur(i, currentCoins, total+coins[i])
currentCoins.pop()
currentCoins = []
recur(0, currentCoins, 0)
return res
m = getMinCoins(coins, amount)
print(m)
a = getMinCoinsArray(coins, amount)
print(a)