
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find number of combinations of coins to reach target in Python
Suppose we have a list of coins and another value amount, we have to find the number of combinations there are that sum to amount. If the answer is very large, then mod the result by 10^9 + 7.
So, if the input is like coins = [2, 5] amount = 10, then the output will be 2, as we can make these combinations − [2, 2, 2, 2, 2], [5, 5]
To solve this, we will follow these steps −
- m := 10^9 + 7
- dp := a list of size same as amount + 1, and fill it with 0
- dp[0] := 1
- for each d in coins, do
- for i in range 1 to size of dp, do
- if i - d >= 0, then
- dp[i] := dp[i] + dp[i - d]
- if i - d >= 0, then
- for i in range 1 to size of dp, do
- return (last element of dp) mod m
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, coins, amount): dp = [0] * (amount + 1) dp[0] = 1 for d in coins: for i in range(1, len(dp)): if i - d >= 0: dp[i] += dp[i - d] return dp[-1] % (10 ** 9 + 7) ob = Solution() coins = [2, 5] amount = 10 print(ob.solve(coins, amount))
Input
[2, 5], 10
Output
2
- Related Articles
- Program to find number of given operations required to reach Target in Python
- Program to find minimum number of buses required to reach final target in python
- C++ program to find minimum number of punches are needed to make way to reach target
- Program to find number of coins needed to make the changes with given set of coins in Python
- C++ program to count number of operations needed to reach n by paying coins
- Program to find number of coins needed to make the changes in Python
- Program to find maximum number of coins we can collect in Python
- Program to find number of minimum steps to reach last index in Python
- Program to find number of distinct combinations that sum up to k in python
- Program to find minimum steps to reach target position by a chess knight in Python
- Program to find maximum number of coins we can get using Python
- Program to find minimum number of hops required to reach end position in Python
- Program to find minimum number of vertices to reach all nodes using Python
- Program to find number of sublists whose sum is given target in python
- Program to find number of distinct quadruple that forms target sum in python

Advertisements