3183. The Number of Ways to Make the Sum π
Description
You have an infinite number of coins with values 1, 2, and 6, and only 2 coins with value 4.
Given an integer n
, return the number of ways to make the sum of n
with the coins you have.
Since the answer may be very large, return it modulo 109 + 7
.
Note that the order of the coins doesn't matter and [2, 2, 3]
is the same as [2, 3, 2]
.
Example 1:
Input: n = 4
Output: 4
Explanation:
Here are the four combinations: [1, 1, 1, 1]
, [1, 1, 2]
, [2, 2]
, [4]
.
Example 2:
Input: n = 12
Output: 22
Explanation:
Note that [4, 4, 4]
is not a valid combination since we cannot use 4 three times.
Example 3:
Input: n = 5
Output: 4
Explanation:
Here are the four combinations: [1, 1, 1, 1, 1]
, [1, 1, 1, 2]
, [1, 2, 2]
, [1, 4]
.
Constraints:
1 <= n <= 105
Solutions
Solution 1: Dynamic Programming (Complete Knapsack)
We can start by ignoring coin $4$, defining the coin array coins = [1, 2, 6]
, and then using the idea of the complete knapsack problem. We define $f[j]$ as the number of ways to make up amount $j$ using the first $i$ types of coins, initially $f[0] = 1$. Then, we iterate through the coin array coins
, and for each coin $x$, we iterate through amounts from $x$ to $n$, updating $f[j] = f[j] + f[j - x]$.
Finally, $f[n]$ is the number of ways to make up amount $n$ using coins $1, 2, 6$. Then, if $n \geq 4$, we consider choosing one coin $4$, so the number of ways becomes $f[n] + f[n - 4]$, and if $n \geq 8$, we consider choosing two coins $4$, so the number of ways becomes $f[n] + f[n - 4] + f[n - 8]$.
Note the modulus operation for the answer.
The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the amount.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|