Coin Change II You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0.
You may assume that you have an infinite number of each kind of coin.
The answer is guaranteed to fit into a signed 32-bit integer.
Example 1:
Input: amount = 5, coins = [1,2,5] Output: 4 Explanation: there are four ways to make up the amount: 5=5 5=2+2+1 5=2+1+1+1 5=1+1+1+1+1
#recursion solution
from typing import List
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
def coin_change(coins, amount, currentIndex):
pass
return coin_change(coins, amount, 0)
Recursion Solution with memoization#
#recursion solution with memoization
from typing import List
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
if amount == 0:
return 0
n = len(coins)
dp = [[-1 for _ in range(amount+1)] for _ in range(len(coins))]
def coin_change(coins, amount, currentIndex):
if amount == 0:
return 1
if amount < 0:
return 0
if currentIndex >= n:
return 0
if(dp[currentIndex][amount])!=-1:
return dp[currentIndex][amount]
#inclusion
c1 = 0
if(coins[currentIndex] <= amount):
c1 = coin_change(coins, amount-coins[currentIndex], currentIndex)
#exclusion
c2 = coin_change(coins, amount, currentIndex+1)
dp[currentIndex][amount] = c1+c2
return dp[currentIndex][amount]
return coin_change(coins, amount, 0)
x = Solution()
print(x)
<__main__.Solution object at 0xffff968e5510>
x.change(5, [1,2,5])
4
dp solution#
from typing import List
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
dp = [[0 for _ in range(amount+1)] for _ in range(len(coins)+1)]
for i in range(len(dp)):
dp[i][0] = 1
for i in range(1,len(dp)):
for j in range(1,len(dp[0])):
c1 = 0
#inclusion
if(coins[i-1] <= j):
c1 = dp[i][j-coins[i-1]]
#exlucsion
c2 = dp[i-1][j]
dp[i][j] = c1 + c2
return dp[-1][-1]
x = Solution()
print(x)
<__main__.Solution object at 0xffff968e58d0>
x.change(5,[1,2,5])
4
from typing import List
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
dp = [0 for _ in range(amount+1)]
dp[0] = 1
for i in range(len(coins)):
for j in range(1,len(dp)):
if coins[i-1] <= j:
dp[j] = dp[j]+ dp[j-coins[i-1]]
return dp[-1]
x = Solution()
x.change(5,[1,2,5])
4