The Number of Ways to Make the Sum Problem
Description
LeetCode Problem 3183.
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 10^9 + 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 <= 10^5
Solution
Approach: Dynamic Programming (Unbounded Knapsack)
First ignore the coin 4 and count the ways to pay with coins [1, 2, 6] using the usual unbounded knapsack: f[0] = 1, and for each coin x and each amount j from x to n, f[j] += f[j - x]. The coin 4 can be used at most twice, so add the cases with one coin 4, f[n - 4], and with two, f[n - 8] (when those amounts are not negative). Take everything modulo 10^9 + 7.
Complexity: O(n) time and O(n) space.
class Solution:
def numberOfWays(self, n: int) -> int:
mod = 10**9 + 7
coins = [1, 2, 6]
f = [0] * (n + 1)
f[0] = 1
for x in coins:
for j in range(x, n + 1):
f[j] = (f[j] + f[j - x]) % mod
ans = f[n]
if n >= 4:
ans = (ans + f[n - 4]) % mod
if n >= 8:
ans = (ans + f[n - 8]) % mod
return ans