-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathCoinChange2.py
More file actions
33 lines (30 loc) · 1.33 KB
/
CoinChange2.py
File metadata and controls
33 lines (30 loc) · 1.33 KB
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
class Solution(object):
def change(self, amount, coins):
"""
:type amount: int
:type coins: List[int]
:rtype: int
"""
if amount == 0:
return 1
#Let us create a DP array.
dp = []
for i in range(len(coins) + 1):
dp.append([0] * (amount+1)) #The reason why we intialize with 0 is worst case, we wont be able to
# make the amount.
dp[i][0] = 1
for i in range(1,len(dp)):
for j in range(1, len(dp[0])):
# If the amount is less that coin being considered, we will skip
# choosing the coin. This is by basically using the value exactly
# above as it is the value that we have in hand for generating the
# same amount without using the current coin.
if j < coins[i-1]:
dp[i][j] = dp[i-1][j]
else:
#Given that we are calculating the total amount, we can simply
#calculate the total amount generated by using the coin and not
#using it.
dp[i][j] = dp[i-1][j] + dp[i][j-coins[i-1]] #dp[i][j-coins[i-1]] <-- remaining amount using the same coin.
#print(dp)
return dp[-1][-1]