Number of Ways to Earn Points Problem
Description
LeetCode Problem 2585.
There is a test that has n types of questions. You are given an integer target and a 0-indexed 2D integer array types where types[i] = [count_i, marks_i] indicates that there are count_i questions of the i^th type, and each one of them is worth marks_i points.
Return the number of ways you can earn exactly target points in the exam. Since the answer may be too large, return it modulo 10^9 + 7.
Note that questions of the same type are indistinguishable.
- For example, if there are
3questions of the same type, then solving the1^stand2^ndquestions is the same as solving the1^stand3^rdquestions, or the2^ndand3^rdquestions.
Example 1:
Input: target = 6, types = [[6,1],[3,2],[2,3]]
Output: 7
Explanation: You can earn 6 points in one of the seven ways:
- Solve 6 questions of the 0^th type: 1 + 1 + 1 + 1 + 1 + 1 = 6
- Solve 4 questions of the 0^th type and 1 question of the 1^st type: 1 + 1 + 1 + 1 + 2 = 6
- Solve 2 questions of the 0^th type and 2 questions of the 1^st type: 1 + 1 + 2 + 2 = 6
- Solve 3 questions of the 0^th type and 1 question of the 2^nd type: 1 + 1 + 1 + 3 = 6
- Solve 1 question of the 0^th type, 1 question of the 1^st type and 1 question of the 2^nd type: 1 + 2 + 3 = 6
- Solve 3 questions of the 1^st type: 2 + 2 + 2 = 6
- Solve 2 questions of the 2^nd type: 3 + 3 = 6
Example 2:
Input: target = 5, types = [[50,1],[50,2],[50,5]]
Output: 4
Explanation: You can earn 5 points in one of the four ways:
- Solve 5 questions of the 0^th type: 1 + 1 + 1 + 1 + 1 = 5
- Solve 3 questions of the 0^th type and 1 question of the 1^st type: 1 + 1 + 1 + 2 = 5
- Solve 1 questions of the 0^th type and 2 questions of the 1^st type: 1 + 2 + 2 = 5
- Solve 1 question of the 2^nd type: 5
Example 3:
Input: target = 18, types = [[6,1],[3,2],[2,3]]
Output: 1
Explanation: You can only earn 18 points by answering all questions.
Constraints:
1 <= target <= 1000n == types.length1 <= n <= 50types[i].length == 21 <= count_i, marks_i <= 50
Solution
Approach: Dynamic Programming
Let f[i][j] be the number of ways to score exactly j points using the first i types. Start with f[0][0] = 1; the answer is f[n][target].
For type i with count questions worth marks each, choose k questions of this type (0 <= k <= count):
f[i][j] = f[i-1][j] + f[i-1][j - marks] + ... + f[i-1][j - count * marks]
(only terms with a non-negative index). Take everything modulo 10^9 + 7.
The time complexity is O(n * target * count) and the space complexity is O(n * target).
class Solution:
def waysToReachTarget(self, target: int, types: List[List[int]]) -> int:
n = len(types)
mod = 10**9 + 7
f = [[0] * (target + 1) for _ in range(n + 1)]
f[0][0] = 1
for i in range(1, n + 1):
count, marks = types[i - 1]
for j in range(target + 1):
for k in range(count + 1):
if j >= k * marks:
f[i][j] = (f[i][j] + f[i - 1][j - k * marks]) % mod
return f[n][target]