Dynamic programming · Medium
A packing tool can use any number of units from each available denomination. It needs to count the different combinations producing an exact amount. The order of chosen units is irrelevant, so counting sequences would overstate the options.
Count unordered combinations of the distinct denominations that sum exactly to the requested amount.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ coins: integer[], amount: integer }
Fields
- coins is an unsorted array of distinct positive integer denominations. Each denomination may be used any number of times.
- amount is the non-negative integer target.
Output
Return value
- Return a numeric integer count. Different orderings of the same multiset count once.
- Amount zero has one empty combination. With no coins, a positive amount has zero combinations.
Constraints
- 0 <= coins.length <= 20; 1 <= coins[i] <= 1000; 0 <= amount <= 1000.
- The final answer is at most Number.MAX_SAFE_INTEGER. Use exact intermediate arithmetic; intermediate counts need not fit a 32-bit integer.
Examples
Example 1
{
"amount": 4,
"coins": [
1,
2
]
}Returns
3Example 2
{
"amount": 3,
"coins": [
2
]
}Returns
0Required complexity
O(c × amount) dynamic-program transitions and O(amount) stored counts