imashutosh51

Coin Change II

Mar 6th, 2026
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.89 KB | None | 0 0
  1. '''
  2. Unbounded 0/1 Knapsack
  3. Same like Coin Change I but here if cur_remaining==0, means you got one combination so return 1
  4. if i<0, means no coins left to select so return 0
  5. dp[i][j]=sum of take+not_take because dp[i][j] denotes the maxium coins composition that is possible by 0->ith coins and target as j
  6. '''
  7.  
  8. def fun(arr,i,cur_remaining, dp):
  9.     if cur_remaining==0:
  10.         return 1
  11.     if i<0:
  12.         return 0
  13.     if dp[i][cur_remaining]!=-1:
  14.         return dp[i][cur_remaining]
  15.     coin=arr[i]
  16.     take=0
  17.     if cur_remaining>=coin:
  18.         take=fun(arr,i,cur_remaining-coin, dp)
  19.     not_take=fun(arr,i-1,cur_remaining,dp)
  20.     dp[i][cur_remaining]=take+not_take
  21.     return dp[i][cur_remaining]
  22.  
  23.  
  24. class Solution:
  25.     def change(self, amount:int, coins: List[int]) -> int:
  26.         dp=[[-1]*(amount+1) for _ in range(len(coins))]
  27.         return fun(coins,len(coins)-1,amount,dp)
Advertisement
Add Comment
Please, Sign In to add comment